While working with the MongoDB driver, mgo, it occurred to me that the topic of errors with type assertion can be somewhat unclear. Consider the following code which performs a bulk insert of documents into the database.
...
var bulkErrs []mgo.BulkErrorCase
var err error
_, err = bulk.Run()
if err != nil {
bulkErrs = err.(*mgo.BulkError).Cases()
for _, case := range bulkErrs {
log.Println(case.Index, case.Err)
}
}
In this example the returned err contains information on all the errors that occurred during the bulk.Run() process.
The type of variable "err" is "error", but in this example type assertion is used so features of the underlying actual concrete type can be used.
Since the built-in type "error" is an interface type, error values can be any concrete type that has a method with the following signature: Error() string.
评论:
natefinch:
kidovate:don't do this:
bulkErrs = err.(*mgo.BulkError).Cases()
The type cast can fail, in which case, this panics
What you want to do is this:
bulkErr, ok = err.(*mgo.BulkError) if !ok { // not a bulk error } for _, case := range bulkErr.Cases() { // }
robe_and_wizard_hat:This isn't so bad, you can do a type switch on your errors to get a catch type syntax.
euank:Yes, it's unfortunate. Perhaps bulk.Run() should have declared to return an
*mgo.BulkError
instead.
Absolutely not! This is one of Go's big gotchas; returning a struct when a caller might expect an interface makes nil comparisons iffy. Always return interfaces when your caller might ever interpret it as such.
Here's an example of how this can shoot you in the foot: https://play.golang.org/p/RBkfTmRQST
Note how 'case 2' can be turned into 'case 3' by some simple refactoring, so even if you start with correct code, it's basically a timebomb to define functions that return like that.
