3

Go 错误处理 errors

 2 years ago
source link: https://wnanbei.github.io/post/go-%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86-errors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Go标准库

Go 错误处理 errors

2020-06-05

阅读时长: 1 分钟

errors 用于增强 Go 的错误处理能力。

Errors

error 类型为一个接口,其定义为:

type error interface {
	Error() string
}

Error

Error() 函数返回一个字符串,用以表示这个 error 类型。

func (e *error) Error() string (
	return e.msg
)

Go 1.13 中新增,可以将 error 嵌套起来,形成多层结构。

简单的嵌套方法,用 Errorf()%w

e := errors.New("原始错误")
w := fmt.Errorf("Wrap了一个错误%w", e)

复杂的自定义类型需要拥有 Unwrap() 方法的 error 类型。

Unwrap() 的定义举例:

type NewError struct {
	err error
	msg string
}

func (e *NewError) Error() string {
	return e.err.Error() + e.msg
}

func (e *NewError) Unwrap() error (
	return e.err
)
e := errors.New("原始错误")
w := &NewError{err: e, msg: "wrap了一个错误"}

Unwrap

Go 1.13 新增,这个函数可以把嵌套在 error 中的 error 取出。

func Unwrap(err error) error

用来判断 err 或者其嵌套链中,是否有 target 类型的异常,只能判断已经生成的特定类型 error,也就是所谓的哨兵异常。

func Is(err error, target error) bool
if errors.Is(err, os.ErrExist)

用来判断 err 或者其嵌套链中,是否有 target 的异常,如果有,就将符合类型的 err 赋值给 target

这种方式只能判断指定的自定义异常类型,也就是 struct

func As(err error, target interface{}) bool
var tar *os.PathError
if errors.As(err, &tar) {
	fmt.Println(perr.Path)
}

Go

Licensed under MIT License

最后更新于 2021-11-09 23:34:24


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK