4 ms·
How do you decorate the errors? In Go I might write a, err := foo() if err != nil { return nil, fmt.Errorf("failed to foo: %v", err) }
by iand 10y ago
How do you decorate the errors? In Go I might write
a, err := foo()
if err != nil {
return nil, fmt.Errorf("failed to foo: %v", err)
}
- beefsack 10y agoIf you want something like this, you'd usually use your own error type to wrap the errors returned from the functions you call. You can implicitly do the conversions and keep the code the same if you implement `From` or `Into` for the wrapped error type.
- ameliaquining 10y agoYou often won't need to change the error object from what foo() returns; Rust errors are generally structs or enums, rather than non-machine-readable strings. But if you do need to change it, it looks like this: foo().map_err(MyError::new)?
- cpuguy83 10y agogo errors are generally backed by structs as well (though not necessarily), even `fmt.Errorf("some error")` is a struct (called `errorString`). `Error() string` is just the interface that things that want to be errors must implement, which ideally gives you the human readable version of the error.
- saghm 10y agoIn Rust, I think it's more idiomatic to just implement the `Display` trait on you error type so that you can generate the string when you need it instead of at the time the error occurs
- dasfasf 10y agoI use error_chain let a = foo().chain_err(|| "failed to foo")?;
- masklinn 10y ago`?` will convert the original error to the one the caller returns so you can implement the decoration in the conversion if that's suitable, otherwise `Result#map_err` lets you convert an error "at the callsite" (and is a noop if there was no error). Alternatively, you can use error_chain: https://brson.github.io/error-chain/error_chain/index.html https://brson.github.io/error-chain/error_chain/index.html.