orlandos-nl / BSON

Native Swift library for BSON (http://bsonspec.org)
https://orlandos.nl/docs/mongokitten/articles/bson
MIT License
109 stars 35 forks source link

Support for a Base BSONError protocol #51

Open Andrewangeta opened 5 years ago

Andrewangeta commented 5 years ago

It will be useful to have a base protocol for BSONErrors that can be handled/caught at a global level for some applications. Currently if we want to catch a BSON error we would have to type cast to all the known types of errors. It would turn code that looks like this:

func handle(error: Error) {
    if let error = error as? BSONValueNotFound {
    ...
    } else if let error = error as? DeserializationError {
    ...
    } else if let error = error as? UnsupportedDocumentDecoding {
    ...
    }
    etc..
}

To code that would look like this:

if let error = error as? BSONError {
...
}
Andrewangeta commented 5 years ago

@Obbut any thoughts on this? 👀

Obbut commented 5 years ago

Hmm, currently all error types in BSON are private/internal, so it is impossible to catch them anyway.

We might implement a BSONError protocol, but another option could be to just convert the errors to an enum. The downside of using an enum is that people can switch over them which makes adding new cases a breaking change, but that can be solved like we did in MeowVapor.

The main upside of using an enum is that it allows writing catch BSONError.valueNotFound.

Joannis commented 5 years ago

I suggested both solutions. The first one to @Andrewangeta and the second one to @Obbut . So far I prefer the second use case more since it allows us to cover more detail in the errors