Skip to main content

ApiError

Struct ApiError 

Source
pub struct ApiError {
    pub code: String,
    pub message: String,
    pub details: Option<Value>,
}
Expand description

A machine-readable JSON error body.

Serializes as:

{ "code": "NOT_FOUND", "message": "item not found" }
{ "code": "VALIDATION_ERROR", "message": "invalid input", "details": { "field": "name" } }

Use the factory methods to get a (StatusCode, Json<ApiError>) tuple, which implements [IntoResponse] and can be returned directly from Axum handlers.

§Example

use axum::response::IntoResponse;
use axum_api_kit::ApiError;

async fn handler() -> impl IntoResponse {
    ApiError::not_found("item not found")
}

Fields§

§code: String

A short, stable, machine-readable error identifier. Use SCREAMING_SNAKE_CASE.

§message: String

A human-readable description of the error.

§details: Option<Value>

Optional structured details (field-level validation errors, etc.).

Implementations§

Source§

impl ApiError

Source

pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self

Construct a bare ApiError without a bundled status code.

Prefer the factory methods (not_found, etc.) when returning responses directly from handlers.

Source

pub fn with_details(self, details: Value) -> Self

Attach structured details to this error.

Source

pub fn bad_request( code: impl Into<String>, message: impl Into<String>, ) -> (StatusCode, Json<Self>)

400 Bad Request with the provided code and message.

Source

pub fn unauthorized(message: impl Into<String>) -> (StatusCode, Json<Self>)

401 Unauthorized - code defaults to "AUTH_REQUIRED".

Source

pub fn forbidden(message: impl Into<String>) -> (StatusCode, Json<Self>)

403 Forbidden - code defaults to "FORBIDDEN".

Source

pub fn not_found(message: impl Into<String>) -> (StatusCode, Json<Self>)

404 Not Found - code defaults to "NOT_FOUND".

Source

pub fn conflict(message: impl Into<String>) -> (StatusCode, Json<Self>)

409 Conflict - code defaults to "CONFLICT".

Source

pub fn unprocessable(message: impl Into<String>) -> (StatusCode, Json<Self>)

422 Unprocessable Entity - code defaults to "VALIDATION_ERROR".

Source

pub fn internal(message: impl Into<String>) -> (StatusCode, Json<Self>)

500 Internal Server Error - code defaults to "INTERNAL_ERROR".

Source

pub fn db_error() -> (StatusCode, Json<Self>)

500 Internal Server Error for database failures - code is "DB_ERROR".

Source

pub fn too_many_requests(message: impl Into<String>) -> (StatusCode, Json<Self>)

429 Too Many Requests - code defaults to "RATE_LIMITED".

Source

pub fn service_unavailable( message: impl Into<String>, ) -> (StatusCode, Json<Self>)

503 Service Unavailable - code defaults to "SERVICE_UNAVAILABLE".

Source

pub fn not_implemented(message: impl Into<String>) -> (StatusCode, Json<Self>)

501 Not Implemented - code defaults to "NOT_IMPLEMENTED".

Source

pub fn with_source(self, source: &str) -> Self

Attach a source error message to this error.

Stores the source in the details field under the "source" key. Can be chained with other builder methods.

§Example
use axum_api_kit::ApiError;

let err = ApiError::new("NOT_FOUND", "user not found")
    .with_source("SELECT * FROM users WHERE id = ?")
    .with_details(serde_json::json!({ "user_id": 42 }));

Trait Implementations§

Source§

impl Clone for ApiError

Source§

fn clone(&self) -> ApiError

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ComposeSchema for ApiError

Source§

impl Debug for ApiError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ApiError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ApiError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<Error> for ApiError

Convert std::io::Error to ApiError with HTTP 500.

Maps std::io::Error to ApiError::internal() with the error message. Enables using the ? operator in handlers:

async fn handler() -> impl IntoResponse {
    let content = std::fs::read_to_string("/data.txt")?;  // auto-converts to ApiError
    Ok((StatusCode::OK, content))
}
Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for ApiError

Convert serde_json::Error to ApiError with HTTP 500.

Maps JSON errors to ApiError::internal() with the error message.

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for ApiError

Available on crate feature sqlx only.

Convert sqlx::Error to an ApiError with a semantically appropriate HTTP status.

Requires the sqlx feature flag.

sqlx::Error variantcodeHTTP
RowNotFoundNOT_FOUND404
Database (unique/FK violation)CONFLICT409
Database (check violation)VALIDATION_ERROR422
Database (other)DB_ERROR500
PoolTimedOut / PoolClosed / WorkerCrashedSERVICE_UNAVAILABLE503
everything elseDB_ERROR500
Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<ValidationErrors> for ApiError

Available on crate feature validator only.
Source§

fn from(errors: ValidationErrors) -> Self

Converts to this type from the input type.
Source§

impl Serialize for ApiError

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl ToSchema for ApiError

Source§

fn name() -> Cow<'static, str>

Return name of the schema. Read more
Source§

fn schemas(schemas: &mut Vec<(String, RefOr<Schema>)>)

Implement reference utoipa::openapi::schema::Schemas for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PartialSchema for T
where T: ComposeSchema + ?Sized,

Source§

fn schema() -> RefOr<Schema>

Return ref or schema of implementing type that can then be used to construct combined schemas.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> ValidateIp for T
where T: ToString,

Source§

fn validate_ipv4(&self) -> bool

Validates whether the given string is an IP V4
Source§

fn validate_ipv6(&self) -> bool

Validates whether the given string is an IP V6
Source§

fn validate_ip(&self) -> bool

Validates whether the given string is an IP
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more