You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Oct 17, 2022. It is now read-only.
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> { ... }typeResult<T> = std::result::Result<T,Error>;// Custom error made using thiserror crate#[derive(thiserror::Error,Debug)]pubenumError{// 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)}