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

Can we create subtypes for errors in Go?

我想在 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)
    }
}

我想要一个包含两个子类型 Error1Error1 的错误类型 CommonError,以便我可以执行以下操作。

func 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: 但是当我遇到大量错误时,或者当我需要对模块内部的错误进行一些抽象时,这种方法就不是最好的方法了。

您可以在一个 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

如果你想 "group" 错误,另一个解决方案是创建一个 "marker" 接口:

type CommonError interface {
    CommonError()
}

Error1Error2 必须实现:

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()
}