Skip to main content

ApiError

Trait ApiError 

Source
pub trait ApiError: Error {
    // Provided methods
    fn status_code(&self) -> StatusCode { ... }
    fn message(&self) -> Cow<'_, str> { ... }
}
Expand description

An error that can be returned by a service API.


#[derive(Debug, thiserror::Error)]
enum MyServiceErrors {
    #[error("Database error: {0}")]
    Db(String),
    #[error("Authentication error")]
    Auth,
// etc...
}

impl ApiError for MyServiceErrors {
    fn status_code(&self) -> StatusCode {
        match self {
            MyServiceErrors::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,
            MyServiceErrors::Auth => StatusCode::UNAUTHORIZED,
        }
    }
    fn message(&self) -> Cow<'_, str> {
        match self {
            MyServiceErrors::Db(_) => "Database error".into(),
            MyServiceErrors::Auth => "Authentication error".into(),
        }
    }
}

assert_eq!(MyServiceErrors::Db("test".to_string()).status_code(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(MyServiceErrors::Auth.status_code(), StatusCode::UNAUTHORIZED);

Provided Methods§

Source

fn status_code(&self) -> StatusCode

Returns the HTTP status code associated with the error.

Source

fn message(&self) -> Cow<'_, str>

Returns a human-readable message describing the error. It can be potentially shown to the user.

Implementors§