Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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) 
    }


You 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)?


go 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.


In 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


If 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.


`?` 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.


I use error_chain

    let a = foo().chain_err(|| "failed to foo")?;




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: