When using a custom Error
type in Go (with extra fields to capture some details), when trying to return nil
as value of this type, I get compile errors like cannot convert nil to type DetailedError
or like cannot use nil as type DetailedError in return argument
, from code looking mostly like this:
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}
}
(full snippet: https://play.golang.org/p/4i6bmAIbRg)
What would be the idiomatic way to solve this problem? (Or any way that works...)
I actually need the extra fields on errors because I have detailed error messages constructed by complex logic from simpler ones etc., and if I would just fall back to "string errors" I'd basically have to parse those strings to pieces and have logic happen based on them and so on, which seems really ugly (I mean, why serialize to strings info you know you're gonna need to deserialize later...)