错误处理,是非常重要的。在go语言中,错误处理被设计的十分简单。

如果做得好,会在排查问题等方面很有帮助;如果做得不好,就会比较麻烦。

从1.0开始,go中定义错误为 error 接口

// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
    Error() string
}

go语言中,错误处理的几种方式:

1、通过判断值相等。像 io.EOF,go语言中,称为 sentinel error

2、通过断言( type assertion or type switch),判断err的类型或者是否实现了某个接口

3、利用包提供的方法。像 os.IsNotExist。go语言中,称为 ad-hoc check

4、当上面3中方式不可用时,通过搜索 err.Error() 是否包含特定字符串。(不被

golang中的错误处理方法