Skip to main content

AppError

Struct AppError 

Source
pub struct AppError {
    pub status: StatusCode,
    pub code: String,
    pub title: String,
    pub detail: Option<String>,
    pub errors: Option<Box<BTreeMap<String, Vec<String>>>>,
    pub headers: Box<HeaderMap>,
    pub source: Option<BoxError>,
}
Expand description

An HTTP error. Handlers, extractors, guards and layers return it; it renders in Navree’s JSON error shape, as application/json:

{"statusCode": 404, "message": "Deal not found", "error": "Not Found", "code": "not_found"}
  • statusCode is the HTTP status.
  • message is the detail when there is one, else the title (the reason phrase by default, and "Internal server error" for 500s). For validation errors it is every field message, flattened in field order.
  • error is the reason phrase of the status ("Not Found").
  • code is the machine-readable code a front end maps to a translation key: one of the framework’s stable codes, or an app’s own (with_code). http.errors.code = false leaves it out.
  • errors (validation errors only) maps fields to their messages:
{"statusCode": 400, "message": ["email must be a valid email address"],
 "error": "Bad Request", "code": "validation_failed",
 "errors": {"email": ["email must be a valid email address"]}}

The request id is in the X-Request-Id response header, not the body. Any error type converts into a 500 with ? (its message is logged, never sent); modules turn their own error types into specific statuses with ModuleBuilderHttpExt::map_error.

AppError deliberately does not implement std::error::Error, which is what makes the blanket From<E: Into<BoxError>> conversion possible.

Fields§

§status: StatusCode

The HTTP status.

§code: String

The machine-readable code, rendered as code ("not_found", "validation_failed", "campaign_already_running"): lower snake case, stable across releases, what a front end maps to a translation key. Empty leaves the member out.

§title: String

The default message, rendered as message when there is no detail: the reason phrase for statuses built with from_status.

§detail: Option<String>

A human-readable explanation of this occurrence, rendered as message.

§errors: Option<Box<BTreeMap<String, Vec<String>>>>

Field errors ({"field.path": ["message"]}), for 400 validation responses. Boxed, like headers, to keep Result<T, AppError> small.

§headers: Box<HeaderMap>

Extra response headers (Retry-After, WWW-Authenticate, …).

§source: Option<BoxError>

The underlying error, logged for 5xx responses and never sent.

Implementations§

Source§

impl AppError

Source

pub fn new( status: StatusCode, code: impl Into<String>, title: impl Into<String>, ) -> Self

An error with an explicit status, code and title (the default message).

Source

pub fn from_status(status: StatusCode) -> Self

The default error for status: its reason phrase as the title, and a code derived from it.

Source

pub fn bad_request(detail: impl Into<String>) -> Self

400 with a message.

Source

pub fn invalid_filter(detail: impl Into<String>) -> Self

400 invalid_filter with a message: a list filter that names an unknown field or has a malformed value.

Source

pub fn unauthenticated() -> Self

401: the request is not authenticated.

Source

pub fn two_factor_required() -> Self

401 two_factor_required "Two-factor authentication required": the password was right, and the account also needs a second factor.

Source

pub fn forbidden() -> Self

403: the user may not do this.

Source

pub fn not_found() -> Self

Source

pub fn conflict(detail: impl Into<String>) -> Self

409 with a message.

Source

pub fn limit_reached(detail: impl Into<String>) -> Self

409 limit_reached with a message: a plan or quota limit stops the change (seats, projects, monthly sends).

Source

pub fn demo_read_only() -> Self

403 demo_read_only "Demo workspaces are read-only.": a write in a workspace that only shows sample data.

Source

pub fn csrf_mismatch() -> Self

403 "Invalid CSRF token": the CSRF token is missing or does not match the session.

Source

pub fn page_expired() -> Self

419 page_expired "Page Expired": the page was open too long, or the session it belongs to changed, so what it sends can’t be trusted. The user reloads and tries again.

Source

pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self

400 with field errors ({"field.path": ["message"]}): message is every field message, flattened in field order, and errors the map.

Source

pub fn payload_too_large(limit: usize) -> Self

413: the request body is larger than limit bytes.

Source

pub fn too_many_requests(retry_after: Duration) -> Self

429 with a Retry-After header (whole seconds, at least 1).

Source

pub fn service_unavailable(detail: impl Into<String>) -> Self

503 with a message.

Source

pub fn internal(err: impl Into<BoxError>) -> Self

500 caused by err. The client sees "Internal server error"; the error is logged.

Source

pub fn with_detail(self, detail: impl Into<String>) -> Self

Sets the message.

Source

pub fn with_code(self, code: impl Into<String>) -> Self

Sets the machine-readable code (lower snake case, such as campaign_already_running); the status and the message stay.

Source

pub fn with_header(self, name: HeaderName, value: HeaderValue) -> Self

Adds a response header.

Source

pub fn with_source(self, source: impl Into<BoxError>) -> Self

Records the underlying error (logged for 5xx responses, never sent).

Source

pub fn body(&self) -> Value

The response body: {"statusCode", "message", "error", "code"}, plus "errors" for validation errors.

Source

pub fn take_from(response: &mut Response) -> Option<AppError>

Takes the error out of a response rendered by into_response, so a pipeline other than the HTTP server’s (navree-micro’s message handlers) can map and log it the way the HTTP error layer does. None for any other response, and once the error has been taken.

Trait Implementations§

Source§

impl Debug for AppError

Source§

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

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

impl Display for AppError

Source§

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

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

impl<E: Into<BoxError>> From<E> for AppError

Any error converts into a 500 (? in handlers), like anyhow.

Source§

fn from(error: E) -> Self

Converts to this type from the input type.
Source§

impl From<ListError> for AppError

Source§

fn from(error: ListError) -> Self

A 400 whose errors map each parameter to its messages.

Source§

impl IntoResponse for AppError

The rendered response carries the error itself, so the pipeline can map and log it.

Source§

fn into_response(self) -> Response

The response.

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

Source§

type Output = T

Should always be Self
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 = !

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

fn try_from(value: U) -> Result<T, !>

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> 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