pub trait ApiError: Error {
// Provided methods
fn status_code(&self) -> StatusCode { ... }
fn message(&self) -> Cow<'_, str> { ... }
fn extended(&self) -> Option<Value> { ... }
}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§
Sourcefn status_code(&self) -> StatusCode
fn status_code(&self) -> StatusCode
Returns the HTTP status code associated with the error.
Sourcefn message(&self) -> Cow<'_, str>
fn message(&self) -> Cow<'_, str>
Returns a human-readable message describing the error. It can be potentially shown to the user.
Sourcefn extended(&self) -> Option<Value>
Available on crate feature axum only.
fn extended(&self) -> Option<Value>
axum only.Returns an optional structured payload to include in the default
axum response body under the "extended" key.
Returning None (the default) omits the field entirely. Override
this when you need to surface machine-readable details (e.g. a list
of invalid fields, a retry-after hint, an upstream error code) in
addition to the human-readable message.
Only available with the axum feature.