I am trying to use Monix Task
with mongo-scala-driver
. I have some trouble understanding Error Handling
val mongoClient: Resource[Task, MongoConnection[Task, DomainModel]] =
MongoTypedConnection.create[Task, DomainModel](
"mongodb:...&authMechanism=SCRAM-SHA-1"
)
mongoClient.use { client =>
val changeStream: Task[ChangeStreamObservable[DomainModel]] =
for {
collection <- client.getMongoCollection("myDatabase", "myCollection")
changes <- client.watchCollection(collection)
} yield changes
...
...
...
.as(ExitCode.Success)
}
This works perfectly well when there are no errors. I want to add error handling to this, (for example to handle incorrect database
and collection
names). My initial attempt based on the docs is to try:
val changeObs: io.Serializable =
Await.result(changeStream
.onErrorHandleWith {
case _: TimeoutException =>
// Oh, we know about timeouts, recover it
Task.now("Recovered!")
case other =>
// We have no idea what happened, raise error!
Task.raiseError(other)
}.runToFuture, 5.seconds)
But this gives me an io.Serializable
. How do I retain a ChangeStreamObservable[DomainModel]
while also having some kind of neat error handling? Appreciate pointers to any patterns that I could study.
BR