0

I don't know, how to detect and handle MongoException in case of MongoDB disconnect

  val pingCmd: Publisher[bson.Document] = mongoCollFactory.db.runCommand(BsonDocument.parse("""{"ping": 1}"""))

detect MongoException which does not connect to the database and then returns MongoException Ex. when pingCmd is success -> HealthCheck.OK then pingCmd failed -> HealthCheck.Failed

Abercrombie
  • 1,012
  • 2
  • 13
  • 22
funnyDev
  • 76
  • 6

1 Answers1

0

If you are writing a function that implies and I/O, and can fail, os highly recomended to encapsulate it in a Either or an Option.

1. Either approach

try{
  val pingCmd:Publisher[bson.Document] = 
   mongoCollFactory.db.runCommand(BsonDocument.parse("""{"ping": 1}"""))
  Rigth(pingCmd)
}catch{
  case e:Exception => Left(e)
}

In another point of the execution, you can handle the exception or log a warning. You can find more info about either in ScalaDoc (https://www.scala-lang.org/api/2.9.3/scala/Either.html)

2. Option approach

Using the monad option, you can have a value in case the operation succeeds, or none value if it fails. This solution provide less information about the error, becouse None does not encapsulate information about the exception, while Either does it.

try{
  val pingCmd:Publisher[bson.Document] = 
   mongoCollFactory.db.runCommand(BsonDocument.parse("""{"ping": 1}"""))
  Rigth(pingCmd)
}.toOption
mikealgo
  • 52
  • 3
  • Thank you for the suggestion, but it is not working. when disconnecting the database, it must be print `Exception`. but it prints `success` – funnyDev Aug 23 '19 at 08:29
  • ``` val eitherPing = try{ val pingCmd:Publisher[bson.Document] = mongoCollFactory.db.runCommand(BsonDocument.parse("""{"ping": 1}""")) Right(pingCmd) }catch{ case e:Exception => Left(e) } eitherPing match { case Right(_) => println(Console.GREEN + s"Success -> " + Console.RESET) case Left(value) => println(Console.RED + s"Failed: $value" + Console.RESET) } ``` – funnyDev Aug 23 '19 at 08:33