Golang mgo 错误

huangapple go评论81阅读模式
英文:

Golang mgo errors

问题

mgo能返回除了QueryError或ErrNotFound之外的错误吗?数据库连接错误怎么处理?

在处理程序的顶部使用类似于带有状态码500的漂亮响应的方式,在出现除了ErrNotFound之外的错误时引发panic,然后进行恢复,这样做是一个好的实践吗?

英文:

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?

答案1

得分: 5

mgo返回的错误集合没有限制,因为它在底层执行了许多操作,这些操作也可能返回错误(DNS解析、连接建立、超时等)。因此,处理mgo的错误的正确方法与大多数地方相同:处理您知道并具有自定义逻辑的错误,并在您不知道的错误上退出。良好的退出包括撤消任何本地副作用(关闭/删除本地创建的文件等),然后将错误返回给调用者,可能使用自定义上下文信息进行修饰或封装。

对于这样的错误,我不会恐慌。恐慌通常用于异常情况,当开发人员在API中做错了事情,或者环境严重损坏时,最好的做法是完全停止,例如。与数据库(或任何与网络相关的内容)的连接应该“预计”偶尔会中断,并且应该适当处理,而不仅仅是记录一个无法区分的崩溃。

如果您有更多详细信息并希望进一步讨论,请转到邮件列表。

英文:

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.

答案2

得分: 3

我相信你可以使用LastError来检查任何错误。大多数返回错误的函数会返回一个标准的Go错误,在函数返回时应该进行检查。

通常,在Go中,你应该在使用panic/recover之前有一些非常特殊的情况。最佳实践是在错误出现时处理错误。

有关更多信息,请参阅错误处理和Go延迟、恐慌和恢复来自The Go Blog

英文:

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.

huangapple
  • 本文由 发表于 2013年10月9日 17:26:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/19268009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定