Rust proper error handling (auto convert from one error type to another with question mark)

Update 2020

The rust programming language is evolving quickly so a new answer can be added! I really liked custom_error but now I think thiserror will be my loved one!

use thiserror::Error;

#[derive(Error, Debug)]
pub enum DataStoreError {
    #[error("data store disconnected")]
    Disconnect(#[from] io::Error),
    #[error("the data for key `{0}` is not available")]
    Redaction(String),
    #[error("invalid header (expected {expected:?}, found {found:?})")]
    InvalidHeader {
        expected: String,
        found: String,
    },
    #[error("unknown data store error")]
    Unknown,
}

This allow change io::Error to DataStoreError::Disconnect with question mark ?. Go here for details

useful links:

  • great blog about using thiserror in combine with anyhow

Other interesting crates:

  • anyhow – Flexible concrete Error type built on std::error::Error
  • snafu – Situation Normal: All Fouled Up – SNAFU is a library to easily assign underlying errors into domain-specific errors while adding context. (similar to thiserror)
  • custom_error – This crate contains a macro that should make it easier to define custom errors without having to write a lot of boilerplate code.

for panics:

  • proc-macro-error – This crate aims to make error reporting in proc-macros simple and easy to use.
  • human-panic – Panic messages for humans. Handles panics by calling std::panic::set_hook to make errors nice for humans.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)