【发布时间】:2019-10-28 00:29:21
【问题描述】:
我想在 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: 但是当我有大量错误时,或者当我需要对模块内的错误进行一些抽象时,这种方法不会是最好的。
【问题讨论】:
-
你可以使用
case Error1, Error2:,这还不够吗? -
问题是当我有大量的错误时,很难把所有的错误都放在这样的地方。另一个问题是,如果我想在另一个模块中使用它,我只想对我遇到的错误进行抽象。
标签: go types error-handling subtype type-switch