4 ms·
Note that this can quite problematic in scenarios where the caller wants to inspect the error (example: was the error an http timeout? or a server error?). Retu
by shaan7 5y ago
Note that this can quite problematic in scenarios where the caller wants to inspect the error (example: was the error an http timeout? or a server error?). Returning the error and letting the topmost call site handle that is usually better.
- mseepgood 5y agoThat's what `errors.Is` is for. https://pkg.go.dev/errors#Is https://pkg.go.dev/errors#Is
- simiones 5y agoIt would be interesting if anyone used error types in Go, but you'll be hard pressed to find libraries that do. return fmt.Errorf() all the way.
- noisem4ker 5y agoIn my experience, errors returned by the standard library and recent third party packages are fairly well discernible, although not in all cases. Note that you don't need custom error types, just exported Error instances. These were in use even before wrapping was introduced with Go 1.13 (2019); one had to compare or type-assert directly instead of unwrapping.
- lox 5y agoYou can use %w in fmt.Errorf to accomplish this.
- simiones 5y agoNot really. If the original error is `fmt.Errorf("divide by 0")`, no amount of `fmt.Errorf("failed to divide: %w")` will help anyone programmatically recognize the error.
- lox 5y agoYup, fair point, I thought we were talking about libraries replacing errors to obscure the original, which absolutely happens. Lots of libraries (e.g aws-sdk) do use typed errors, so wrapping them correctly for smaller libraries that compose them is important.
- lu4p 5y agoNo you should use errors.Is(err, http.ErrHandlerTimeout) instead of simple equality.
- shaan7 5y agoThanks (and to mseepgood as well). TIL :)