为了账号安全,请及时绑定邮箱和手机立即绑定

我们可以为 Go 中的错误创建子类型吗?

我们可以为 Go 中的错误创建子类型吗?

Go
明月笑刀无情 2023-06-26 15:31:07
我想在 Go 中创建层次结构错误。我们可以在 Go 中实现这一点吗?例如,我有以下两个错误。type Error1 struct {    reason string    cause error}func (error1 Error1) Error() string {    if error1.cause == nil || error1.cause.Error() == "" {        return fmt.Sprintf("[ERROR]: %s\n", error1.reason)    } else {        return fmt.Sprintf("[ERROR]: %s\nCaused By: %s\n", error1.reason, error1.cause)    }}type Error2 struct {    reason string    cause error}func (error2 Error2) Error() string {    if error2.cause == nil || error2.cause.Error() == "" {        return fmt.Sprintf("[ERROR]: %s\n", error2.reason)    } else {        return fmt.Sprintf("[ERROR]: %s\nCause: %s", error2.reason, error2.cause)    }}我想要一个由两个子类型和CommonError组成的错误类型,以便我可以执行以下操作。Error1Error1func printType(param error) {    switch t := param.(type) {    case CommonError:        fmt.Println("Error1 or Error 2 found")    default:        fmt.Println(t, " belongs to an unidentified type")    }}有办法实现这一点吗?编辑:在类型切换中,我们可以像这样使用多个错误: case Error1, Error2:但是当我有大量错误时,或者当我需要对模块内的错误进行一些抽象时,这种方法不会是最好的方法。
查看完整描述

1 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您可以在 a 中列出多种类型case,因此这将执行您想要的操作:


switch t := param.(type) {

case Error1, Error2:

    fmt.Println("Error1 or Error 2 found")

default:

    fmt.Println(t, " belongs to an unidentified type")

}

测试它:


printType(Error1{})

printType(Error2{})

printType(errors.New("other"))

输出(在Go Playground上尝试):


Error1 or Error 2 found

Error1 or Error 2 found

other  belongs to an unidentified type

如果你想对错误进行“分组”,另一个解决方案是创建一个“标记”接口:


type CommonError interface {

    CommonError()

}

其中Error1和Error2必须实施:


func (Error1) CommonError() {}


func (Error2) CommonError() {}

然后你可以这样做:


switch t := param.(type) {

case CommonError:

    fmt.Println("Error1 or Error 2 found")

default:

    fmt.Println(t, " belongs to an unidentified type")

}

用同样的方法测试,输出是一样的。在Go Playground上尝试一下。


如果您想将CommonErrors 限制为“true”错误,还可以嵌入该error接口:


type CommonError interface {

    error

    CommonError()

}


查看完整回答
反对 回复 2023-06-26
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信