doujiu5464 2015-07-09 17:34
浏览 32

基于Go中错误类型的细粒度错误处理

TLDR: There is a function in some library, which does something over network and may fail with error. Error may indicate bad input parameter, invalid credentials, network failure... And... I don't know what else. And that's the question.

How do I know, what errors to expect, to handle, say, network failures properly.

Long version: It is a very common way to handle errors like that in Go code

function f0() (v Value, err Error) {
  v2, err := f3()
  if err != nil {
    return
  }

  v1, err := f2(v2)
  if err != nil {
    return
  }

  v, err = f1(v1)
  return
}

It is also very common in Go code to not document type of error returned. Let's not forget about another common idiom in Go

err = errors.New("Boo! I failed") // returns trivial errorString

This leads to the situation where caller of f0() can get dozens of errors (if f3() to f1() in my example also do some calls) which represent conceptually different issues.

How to differentiate between all those errors?

  • 写回答

1条回答 默认 最新

  • dqy006150 2015-07-09 17:38
    关注

    Anything implementing this minimal interface is an error;

    type error interface {
        Error() string
    }
    

    The easy solution is;

    type BadCredsError string
    
    func (e BadCredsError) Error() string {
          return string(e)
    } 
    

    Basically, just define your own types and then you can use a type switch or type assertion to determine the specific error types like you see in more OO languages such as C# and Java.

    By the way, my sample is like a 2 seconds pseudo code snippet. The go blog discusses far more in depth here; http://blog.golang.org/error-handling-and-go

    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?