Can we create subtypes for errors in Go?

不羁岁月 提交于 2019-12-13 02:51:02

问题


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

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 ?

Edit:

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.


回答1:


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

Testing it:

printType(Error1{})
printType(Error2{})
printType(errors.New("other"))

Output (try it on the Go Playground):

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

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


来源:https://stackoverflow.com/questions/56580030/can-we-create-subtypes-for-errors-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!