6 ms·
I agree, the lack of stack traces can be annoying when debugging Go programs. Instead of returning raw errors everywhere, the problem can be alleviated by addin
by eadan 6y ago
I agree, the lack of stack traces can be annoying when debugging Go programs. Instead of returning raw errors everywhere, the problem can be alleviated by adding some context to returned errors:
if err := foo(x); err != nil {
return fmt.Errorf("foo: bad argument %s", x)
}
- julvo 6y agoThe problem with this is, that the caller of the function which returns what you wrote (i.e. a dynamic error message) can't match the error anymore for conditional error handling. That's because errors in go are just strings. I guess a solution could be to provide an error matching function but that seems quite cumbersome compared to typed errors.
- arp242 6y agoYou should never match against "err.Error()" for conditional error handling, a better solution is to use a custom error type. There are a bunch of different ways to approach this in Go.
- julvo 6y agoAh that's better, thanks. here a link for others who are reading this https://gobyexample.com/errors https://gobyexample.com/errors
- apta 6y agoExcept most libraries do nothing of the sort, so you end up having to do a substring search.
- arp242 6y agoI've rarely run in to this, but if you do then I'd expect most people will be happy to accept a PR.
- deleted 6y ago[deleted]
- majewsky 6y agoThis problem has been addressed in Go 1.13 with wrapped errors. If you get an error from a filesystem operation, you can return fmt.Errorf("ListThings failed: %w", err) which is a different error type, but the caller can downcast it into the original filesystem error type (even across multiple layers of wrapping) if they're interested in specifically these types of errors.
- apta 6y agoSo re-invent exceptions, but in an inferior way.