小编典典

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

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

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

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


阅读 217

收藏
2020-07-02

共1个答案

小编典典

您可以在中列出多个类型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()
}

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()
}
2020-07-02