Reader

探讨一下错误处理策略, 关于 if err != nil {

| V2EX - 技术 | Default

起因是看到 https://v2ex.com/t/1128449?p=1#reply41 写了

"相比之下 if err != nil 95%的时候都很不优雅"

好像我也看到很多吐槽 Go 错误处理语法的, 以下错误处理策略摘录自<<The Go Programming Language>> :

  1. Propagate the error. # 上抛
  2. Retry the failed operation. # 重试
  3. If progress is impossible, the caller can print the error and stop the program gracefully. # 严重错误, 退出程序
  4. It’s sufficient just to log the error and then continue, perhaps with reduced functionality. # 打印错误, 服务降级运行
  5. In rare cases we can safely ignore an error entirely. # 忽略错误

有无更优雅的方式能够实现上面的处理策略?

已知的两种:

  1. try except finally 除了实现 1 (上抛)优雅点, 剩下的也没看出多大优势,而且错误发生点和处理点不在同一处,这就注定需要额外的代码来重构上下文, 比如,打开 file1, 然后 file2, 但在打开第 file2 时发生错误,处理的时候得先判定是打开哪个文件出错了,再执行相应错误处理和回滚操作。
  2. 还有 Optional 一类的,和 if 没太大区别,只不过前者在语法上做了强制(不检查错误,不能拿到结果),还有一些语法糖( user?.address)。