前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go: 如何创建一个自定义错误

go: 如何创建一个自定义错误

作者头像
超级大猪
发布2021-09-29 15:24:41
9650
发布2021-09-29 15:24:41
举报
文章被收录于专栏:大猪的笔记大猪的笔记

这里以封装http.Status为例。

实现Error() string接口

实现Error() string接口就可以定义一个自定义 error。

代码语言:javascript
复制
type ErrWithStatusCode struct {
    msg  string
    code int
}

func (e ErrWithStatusCode) Error() string {
    return e.msg
}

实现Is(error) bool, As(interface{}) bool接口

在go 1.13后,系统库中添加了两个函数errors.Is, errors.As。用来处理error多重包装问题。 这也使得实现自定义error,如果不实现Is/As两个接口,将会产生严重的兼容问题。这会使得对它调用errors.Is/errors.As失败。

代码语言:javascript
复制
func NewErrWithStatus(msg string, code int) error {
    msg = fmt.Sprintf("%v; error status:%v", msg, code)
    return &ErrWithStatusCode{msg, code}
}

type ErrWithStatusCode struct {
    msg  string
    code int
}

func (e ErrWithStatusCode) Error() string {
    return e.msg
}

func (e *ErrWithStatusCode) Is(tgt error) bool {
    switch tgt.(type) {
    case *ErrWithStatusCode, ErrWithStatusCode:
        return true
    }
    return false
}

// As e、target对应 errors.As(e, target)参数
func (e *ErrWithStatusCode) As(target interface{}) bool {
    switch v := target.(type) {
    case *ErrWithStatusCode:
        v.code = e.code
        v.msg = e.msg
        return true
    }
    return false
}

验证:

代码语言:javascript
复制
func TestErrWithStatusCode_IsAs(t *testing.T) {
    err := NewErrWithStatus("hello", http.StatusBadGateway)
    err1 := fmt.Errorf("%w, world", err) // 使用 fmt.Errorf(%w),添加一个包装后的error。
    flag := false
    if errors.Is(err1, ErrWithStatusCode{}) {// 因为实现了Is接口,可以对它使用系统库对它进行断言
        flag = true
        logrus.Infof("err is ErrWithStatusCode:%v", err)
    }

    assert.Equal(t, flag, true)

    tp := new(ErrWithStatusCode)
    if errors.As(err1, tp) { // 因为实现了As接口,可以还原它的具体数据
        logrus.Infof("%v %v", tp.code, tp)
        assert.Equal(t, tp.code, 502)
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-09-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现Error() string接口
  • 实现Is(error) bool, As(interface{}) bool接口
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档