dougai0138 2013-10-09 09:26
浏览 76

Golang 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?

  • 写回答

2条回答 默认 最新

  • dtcu5885 2013-10-09 21:36

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • doudi8298 2013-10-09 10:04

    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.




  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥30 单片机实验pc软件完全,可以私我商议
  • ¥20 #关于multisim绘图遇到的问题
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去
  • ¥20 用matlab的pdetool解决以下三个问题
  • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
  • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
  • ¥20 h3c静态路要求有详细过程
  • ¥15 调制识别中输入为时频图,星座图,眼图等