1

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

4

1 回答 1

3

您可以在 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()
}

Which Error1 and Error2 must implement:

func (Error1) CommonError() {}

func (Error2) CommonError() {}

And then you can do:

switch t := param.(type) {
case CommonError:
    fmt.Println("Error1 or Error 2 found")
default:
    fmt.Println(t, " belongs to an unidentified type")
}

Testing it with the same, output is the same. Try it on the Go Playground.

If you want to restrict CommonErrors to be "true" errors, also embed the error interface:

type CommonError interface {
    error
    CommonError()
}
于 2019-06-13T12:07:33.583 回答