Frage

Can anyone explain me what is happening with this code? There is no database running because the idea is to catch the exception.

val col = MongoConnection("localhost")("myDB")("myCol")

// Using Try to catch any exception but there is NO exception
// ex1
val ex1 = Try{col.find()}


// Using Try to catch any exception, now we have an exception
// ex2
val ex2 = Try{col.findOne()}

When executing ex2 the exception is caught by Try so

ex2: scala.util.Try[Option[a.T]] = Failure(com.mongodb.MongoException$Network: Read operation to server localhost/127.0.0.1:27017 failed on database myDB)

Why in the ex1 example cant the exception be caught (ex1 doesnt exists after running that code)?

EDIT

Seems that:

val ex1 = Try {col.find().toList}

puts the exception inside the Try into ex1

War es hilfreich?

Lösung

The way connection is implemented is quite lazy.

val col = MongoConnection("localhost")("myDB")("myCol") just creates a description of a connection, does not actually try to connect to DB unless you perform some operation on it.

The same goes for col.find() - it returns a cursor that is not evaluated yet. In other words it's not an open cursor in DB, but a lazy Scala cursor. Once you try to evaluate it by iterating over it it will try to actually run it and will fail.

This is current behavior for Casbah that uses deprecated Mongo Java class: def apply(host: String): MongoConnection = new MongoConnection(new com.mongodb.Mongo(host)) in MongoConnection object. It's suggested to use MongoClient instead of MongoConnection but it will behave in the same way in terms of when it connects to DB.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top