ReactiveMongo/ReactiveMongo — pull request #96 by justwrote (2013-07-25 15:26:59+00:00)
Title: Exceptions as control flow

While profiling my app I saw a lot of exceptions thrown by reactivemongo, namely `DocumentKeyNotFound` and `ClassCastException` - actually I got **27500** `DocumentKeyNotFound`s and **10600** `ClassCastException`s in a very short period of time!

The `DocumentKeyNotFound` exception is thrown by the `BSONDocument.getTry` method which is unnecessary since we could also just return a `Failure` containing this exception. That should be a lot faster since it must not be caught.

The `ClassCastException` exception is thrown by the `BSONDocument.getAsTry` method if `element` is a `BSONNull` and the reader cannot be cast to a `BSONNull` reader - that should affect all `BSONValue`s except `BSONBoolean`. Since everything happens in the `Try` this exception gets caught unnoticed and a `Failure` is returned. In my fix I first check if `element` is of type `BSONNull` and the implicit reader can handle it. If this is not the case I return a `Failure(DocumentKeyNotFound(..))` otherwise I do the same as previously. I just pulled out the casting since I think this kind of exception should bubble up because it indicates a bigger problem which needs attention.

What do you think?