145 points · by bootload · 10y ago · 89 comments
What's worse, is this solution doesn't solve random third-party packages you depend on all that much since they'll still use the utterly useless std-library error package or their own variation which won't necessarily be compatible.
There is no general and reliable way to handle specific types of errors.
And there is no way to add instance specific information to errors in a later version of a package, because that would require using an error type instead of (or in addition to) the existing well known error value, which breaks callers.
1. Assert error behavior not type or message, i.e. the error has a specific method. NOT `type HTTPError struct {Message string;Code int;}` but instead `type HTTPError interface {error;HTTPCode() int;}`. This decouples the location and specific implementation of the error type from the extra information you're adding to it.
(Corollary: Interfaces are Go's only real way to create custom generics. You'll be much happier if you can map your problem space onto interfaces.)
2. Number 1 doesn't help when you wrap errors, because the wrapping error hides any methods on the original. Dave's errors package helps with errors.Cause() that exposes the original error so you can apply #1 effectively.
[0]: http://dave.cheney.net/2016/04/27/dont-just-check-errors-han...
But the standard library uses sentinel errors everywhere and third party packages often do the same. That's what creates the inconsistent and messy status quo of handling different types of errors. It's also not going to change because sentinel errors can never be changed into anything different without breaking clients of the API. No call specific message or other data will ever be added to these standard error values.
Yes you can. Errors are interfaces, not values. As long as you define an Errror() method your struct behaves as an error, but it can have anything a struct has, such as specific information.
You should read Dave's previous presentation (http://dave.cheney.net/paste/gocon-spring-2016.pdf) to understand a bit more about what's already possible today and why Dave's package makes it easier.
var Error = ...
func Get(url string) (result, error) {
if ... {
return Error
}
}
Users of your package would do something like this r, err := net.Get("http://example.com")
if err == net.Error {
//handle this particular error
}
What if you decide that there are in fact different types errors or you want to return an error code with each error? How would you do that?The language problem is that laziness is enabled. The real, practical problem is that programmers are lazy.
It would be nice if at some point the standard library would be scrubbed of string errors. But for the most part, the standard libraries errors that are sane to disambiguate are disambiguated, either with error types or helper functions.
(a) err == pkg.Err
(b) pkg.IsXYZError(err)
(c) switch err := err.(type)
If (c) is discouraged, as some have claimed on this thread, then how are we supposed to access type specific data?
So almost all packages either return a base error, or a custom error type that adheres to the error interface.
>Some errors can only be identified by value and others can only be identified by type
Let's say I'm reading a csv file, and I need to check whether I'm done reading the file - I'd do something like so:
if _, err := csvReader.Read(); err == io.ErrEOF {
quit()
}
However (I can't think of an example off the top of my head), there are many library that make you check the error type to find out what went wrong. if c_err, ok := err.(LibError); ok {
c_err.Code
}
I commonly see this version in libraries that need to return an error with a non-static message (such as the `hostname goolge.com could not be reached`).Go errors are not exceptions.
There is no error package, perhaps you mean the errors package. But it doesn't matter how you create your error in Go as long as you assert for behavior, because errors are interfaces. That is the point really.
If you import a package that uses Dave's error package, in general, you don't need to import Dave's package. That is the point of interfaces, to decouple things.
Firstly, "to reliably get error stacks" doesn't mean "to get stack traces"; it means "to get stack traces attached to errors". You do indeed need Dave's package, or some equivalent, for that; it's not something the standard way of creating errors gives you.
Secondly, "this solution doesn't solve random third-party packages you depend on all that much since they'll still use the utterly useless std-library error package" doesn't refer to the situation where "you import a package that uses Dave's error package", but the converse - if you import a package that uses the standard way of creating errors, you won't get stack traces on those errors. That's true, and it's why Dave's package provides the Wrap function as a partial mitigation.
Of course (s)he does. Why even point that out...?
The standard library's error package recording call stacks as this one does.
The standard library's error package supporting more rich information than just a string, but having both a message, a parent error (recursive data structure), a code-location (package / file / line number), and structured metadata available.
Rich tooling as rust has in the form of Either + macros to make it easy to do the right thing(tm)
... And I know most people won't like this, but exceptions would also solve this. Note all the above suggestions are viable without exceptions, but exceptions are a fine solution in their own right.
This really is just an area the standard library is utterly deficient in (much like logging), and the lack of macros, generics, and sum types makes elegant error handling much more difficult.
(Note: post edited to remove snark.)
The thing that really sells it to me is the being able to wrap the error when necessary with errors.Wrap and find the underlying cause with errors.Cause. I've yet to experiment with the new formatting `%+v` but I can see that coming in useful too.
There have been earlier attempts at something similar (eg https://github.com/juju/errors) but none with the same clarity of thought.
So thanks for a great package Dave and for taking the time to whittle it down into the simplest, most elegant thing.
Honestly I don't know why stack traces aren't formatted for quick parsing. Many thanks to maruel [1] for the inspiration.
My package in it's entirety is:
package errors
const ErrUnknown = 0
type RESTError struct {
HTTPStatus int `json:"-"`
Code int `json:"code,omitempty"`
Message string `json:"error"`
Err error `json:"-"`
}
func (e *RESTError) Error() string {
return e.Message
}
func New(status int, code int, message string) *RESTError {
return &RESTError{HTTPStatus: status, Code: code, Message: message}
}
Doc comments removed just to show the code and nothing else.When those errors finally get back to my web handlers, a standard renderError wraps all errors:
func renderError(w http.ResponseWriter, err error) int {
if e, ok := err.(*errors.RESTError); ok {
return render.JSON(w, e.HTTPStatus, e)
}
e = errors.New(http.StatusInternalServerError, errors.ErrUnknown, err.Error())
return render.JSON(w, e.HTTPStatus, e)
}
I handle all errors as soon as possible and then immediately assign the HTTP status code that should be returned, the error code to enable an external system to look up the error (without string parsing), a sanitised error message (to allow devs to get an idea without looking up the code) and I do put the original error in the Err so that my log files can contain the raw underlying error.It effectively acts as a map between internal errors, and external communication of errors, and allows the place where the error occurred to say "this HTTP status". And because the Err is never stringified I am comforted that internal sensitive data (this is a billing system and unsanitised data should never be leaked even via error messages) does not get leaked.
That's my goal, to handle the error in the way that allows it to best communicate to:
1. HTTP clients via the status
2. Developers via an error code and sanitised message (which they can use to communicate to users)
3. SREs via detail in the secure logs
I found the native errors nice, but not the best for dealing with my 3 audiences.
type AppError struct { Code int Message string InternalMessage string Time time.Time HttpCode int }
All my errors are handled in a http handler function. Before that these errors are produced in any functions called by my handler functions.
I concatenate in to the InternalMessage var any error message I want to log, basically anything I want to show an admin. The message tag will have anything I want to show a user. Normally separated by a semicolon.
Because of this I can give good errors to my users, and I have enough information when something goes wrong.
The only negative might be that, the internal error logs are a bit verbose.
the code above should be
type AppError struct {
Code int
Message string
InternalMessage string
Time time.Time
HttpCode int
}https://github.com/go-kit/kit/blob/master/examples/shipping/...
and more recently https://github.com/go-kit/kit/blob/master/examples/addsvc/tr...
So http 4000 is bad request , but in the business logic terms
This technique and the OP show the power of "programming errors" in Go.
If I'm calling `foo.Bar()` directly, I already have a direct dependency on package `foo`, so what difference does it make to have another one to get `foo.BarError`?
If I'm calling `foo.Bar()` indirectly, then it's true that checking `foo.ErrorType` introduces a novel dependency upon `foo`, but it's equally true that:
a) my direct dependency is frequently going to check and wrap that error in some other type anyway, and
b) I can still use the interface trick that Dave describes to avoid a dependency on `foo`.
I don't see why forcing callers to declare helper interfaces every single time they want to inspect an error is preferable to them only having to do that as a rare workaround.
The difference is that the latter has to be translated to be useful (even when your user understands english).