Skip to content
This repository was archived by the owner on Oct 17, 2022. It is now read-only.
This repository was archived by the owner on Oct 17, 2022. It is now read-only.

Using thiserror for custom error type #32

@future-highway

Description

@future-highway

The thiserror crate is a common library used for creating custom library errors.

Code similar to the below can be placed in the lib.rs file. I added some comments to help explain the crates usage, but the docs page gives great and more advanced examples. While the docs do say a struct can be used instead of an enum, I prefer an enum.

// Define our own result type where the error is our custom error type
// Usage example: fn i_may_fail() -> crate::Result<DidntFailType> { ... }
type Result<T> = std::result::Result<T, Error>;

// Custom error made using thiserror crate
#[derive(thiserror::Error, Debug)]
pub enum Error {
    // If we want to pass through all io errors the from attribute will make this easier by
    // automatically implementing .into() (impl of from gives impl of into for free)
    #[error("an io related error occurred: {0}")]
    Io(#[from] io::Error),
    // This is our first custom type, where the error is just a String.
    // We can't use from because CustomErrorVariant2 also takes just a String
    #[error("CustomErrorVariant1: {0}")]
    CustomErrorVariant1(String),
    #[error("CustomErrorVariant2: {0}")]
    CustomErrorVariant2(String),
    // I'm not sure how I feel about a catch-all variant, but it is an option too.
    // transparent isn't exclusive to the catch-all variant, we could have used it on Io too, for example
    #[error(transparent)]
    Other(#[from] anyhow::Error)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions