Search code examples
gomgo

Golang mgo errors


Can mgo return error different than QueryError or ErrNotFound? What with database connection errors?

Is it a good practise to panic on error different than ErrNotFound and recover on the top of http handlers stack with something like pretty response with status 500?


Solution

  • The set of errors returned by mgo is not constrained, because it does a number of operations underneath that may also return errors (DNS resolution, connection establishment, timeouts, etc). So the proper way to handle errors with mgo is the same as most places: handle the ones you do know about and have custom logic for, and bail out on the ones you don't. Good bailing out encompasses undoing any local side-effects (close/remove locally created files, etc), and then returning the error to the caller, perhaps decorated or wrapped with custom context information.

    I wouldn't panic on such errors. Panics are usually for abnormal situations, when the developer did something wrong with the API, or the environment is seriously damaged and the best course of action is to stop altogether, for example. A connection with the database (or anything network related) should be expected to fall down every once in a while, and handled appropriately rather than just logging an undistinguishable crash.

    If you have more details and would like to talk further, please come over to the mailing list.