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

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题