我们可以为Go中的错误创建子类型吗? [英] Can we create subtypes for errors in Go?

查看:153
本文介绍了我们可以为Go中的错误创建子类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中创建分层错误.我们可以在Go中实现吗? 例如,我有以下两个错误.

I want to create hierarchical errors in Go. Can we achieve this in Go ? For an example, I have following two errors.

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,它由两个子类型Error1Error1组成,因此我可以执行以下操作.

I want to have an error type CommonError which consists of two sub-types, Error1 and Error1, so that I can do the following.

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

有没有办法做到这一点?

Is there a way to achieve this ?

在类型切换中,我们可以使用多个错误,如下所示: case Error1, Error2:,但是当我遇到大量错误时,或者需要对模块中的错误进行某种抽象时,这种方法将不是最佳方法.

In the type switch we can use multiple errors like this: case Error1, Error2: but When I have a larger number of errors, or when I need some abstraction for the errors inside a module, this approach won't be the best one.

推荐答案

您可以在case中列出多种类型,因此可以满足您的要求:

You may list multiple types in a case, so this will do what you want:

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

输出(在游乐场上尝试):

Error1 or Error 2 found
Error1 or Error 2 found
other  belongs to an unidentified type

如果要对错误进行分组",另一种解决方案是创建标记"界面:

If you want to "group" the errors, another solution is to create a "marker" interface:

type CommonError interface {
    CommonError()
}

Error1Error2必须实现:

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.

如果要限制CommonError为"true"错误,请同时嵌入error界面:

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

type CommonError interface {
    error
    CommonError()
}

这篇关于我们可以为Go中的错误创建子类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆