Skip to content

Instantly share code, notes, and snippets.

@xpe
Created December 19, 2019 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpe/f83f09b5e7faf1337c5ec17f12316875 to your computer and use it in GitHub Desktop.
Save xpe/f83f09b5e7faf1337c5ec17f12316875 to your computer and use it in GitHub Desktop.
Rust Error Handling

Rust Error Handling

Some resources:

Crates for Rust Error Handling

simple-error

simple-error is a Rust library that provides a simple Error type backed by a String. It is best used when all you care about the error is an error string.

anyhow

This library provides anyhow::Error, a trait object based error type for easy idiomatic error handling in Rust applications.

Comparison to failure: The anyhow::Error type works something like failure::Error, but unlike failure ours is built around the standard library's std::error::Error trait rather than a separate trait failure::Fail. The standard library has adopted the necessary improvements for this to be possible as part of RFC 2504.

Comparison to thiserror: Use Anyhow if you don't care what error type your functions return, you just want it to be easy. This is common in application code. Use thiserror if you are a library that wants to design your own dedicated error type(s) so that on failures the caller gets exactly the information that you choose.

thiserror

This library provides a convenient derive macro for the standard library's std::error::Error trait.

Thiserror deliberately does not appear in your public API. You get the same thing as if you had written an implementation of std::error::Error by hand, and switching from handwritten impls to thiserror or vice versa is not a breaking change.

fehler

Der Fehler is a library to add support for "throwing functions" to Rust through procedural macros. Functions marked with the throws attribute return Result, but the "Ok" path is used by default and you don't need to wrap ok return values in Ok. To throw errors, use ? or the throws macro.

snafu

SNAFU is a library to easily assign underlying errors into domain-specific errors while adding context.

failure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment