3 ms·
Many errors in go are simply: var ErrFoo = errors.New("error doing Foo") Sometimes if you want an error to have a specific type, but have a custom error m
by NateDad 12y ago
Many errors in go are simply:
var ErrFoo = errors.New("error doing Foo")
Sometimes if you want an error to have a specific type, but have a custom error message with context in it (like the name of the file that was missing, for ErrFileNotFound) you can do something like this:
type ErrBar struct {
error
}
Then you can return errors of that type thusly:
func Do(s string) error {
// ...
return ErrBar{ fmt.Errorf("failed to use %q", s) }
}
Finally, a lot of the time you just want to give the caller some information about an error you received from a function you called, so you just wrap it thusly:
func DoIt() error {
// ...
if err := parseConfig(); err != nil {
return fmt.Errorf("can't parse foo config: %s", err)
}
}
That'll give you an error with a useful message (adding context to the error from getConfig), but with an anonymous type.
And since errors are just regular values, you can check for them in all the same ways you would for any other value (== for errors that are static values, type assertions to check for the type, etc).
It's not super different from Rust's errors, except that with embedding and the implicit interfaces, you don't have to explicitly tell the compiler quite so much to make your error a valid error.
Rust's main difference is the ability to define some automatic conversions and the try! macro that will do an automatic return if the call fails... which are definitely cool.
- masklinn 12y ago> Many errors in go are simply: > var ErrFoo = errors.New("error doing Foo") That's just a matter of having a built-in struct for generic errors no? Rust could probably provide a trivial error type (implementing the relevant traits) for this case.
- NateDad 12y agoYeah,that's a good point. Certainly Rust or anyone else could implement a simple function that returns a populated error struct with the given string message. I guess my initial reaction of a lot of boilerplate was mainly due to the default Rust error having a message, description, and a cause, instead of Go's default error that just has the message. Adding a description and cause is easy enough, and if you defined them for every error in Go, it would probably look pretty similar. My apologies.
- burntsushi 12y ago> I guess my initial reaction of a lot of boilerplate was mainly due to the default Rust error having a message, description, and a cause, instead of Go's default error that just has the message. The `Error` trait in Rust only demands that you define the `description` method.[1] The other two are optional. [1] - http://doc.rust-lang.org/std/error/trait.Error.html http://doc.rust-lang.org/std/error/trait.Error.html