Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang mgo errors

Tags:

go

mgo

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?

like image 774
Rafał Sobota Avatar asked Feb 15 '23 01:02

Rafał Sobota


2 Answers

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.

like image 122
Gustavo Niemeyer Avatar answered Feb 26 '23 21:02

Gustavo Niemeyer


I believe you can check any error with LastError. Most of the error returning functions return a standard Go error that should be checked upon function return.

Usually, in Go, you'd want some very special use case before resorting to panic / recover. It's best practice to handle the errors as they arise.

For more info see Error handling and Go and Defer, Panic, and Recover from The Go Blog.

like image 24
Intermernet Avatar answered Feb 26 '23 21:02

Intermernet