【发布时间】:2017-09-03 10:32:13
【问题描述】:
在 Go 中使用自定义 Error 类型时(使用额外字段来捕获一些详细信息),当尝试将 nil 作为此类型的值返回时,我会收到类似 cannot convert nil to type DetailedError 或 cannot use nil as type DetailedError in return argument 之类的编译错误,从代码看起来大多是这样的:
type DetailedError struct {
x, y int
}
func (e DetailedError) Error() string {
return fmt.Sprintf("Error occured at (%s,%s)", e.x, e.y)
}
func foo(answer, x, y int) (int, DetailedError) {
if answer == 42 {
return 100, nil //!! cannot use nil as type DetailedError in return argument
}
return 0, DetailedError{x: x, y: y}
}
(完整的sn-p:https://play.golang.org/p/4i6bmAIbRg)
解决这个问题的惯用方法是什么?(或任何可行的方法......)
我实际上需要额外的错误字段,因为我有详细的错误消息,这些错误消息是由复杂逻辑从更简单的逻辑等构建的,如果我只是回到“字符串错误”,我基本上必须解析 将这些字符串分解成碎片并根据它们发生逻辑等等,这看起来真的很难看(我的意思是,为什么要序列化到字符串信息,你知道以后需要反序列化......)
【问题讨论】:
标签: go error-handling compiler-errors null