Skip to main content

JsonApiError

Struct JsonApiError 

Source
pub struct JsonApiError {
    pub code: ErrorCode,
    /* private fields */
}
Expand description

An error on its way to becoming a JSON:API error object.

Fields§

§code: ErrorCode

Implementations§

Source§

impl JsonApiError

Source

pub fn in_request(code: ErrorCode, ctx: &Context) -> Self

An error in a request’s context.

The usual constructor: every error a handler returns should carry the correlation id, so taking the context up front is one call rather than a .in_context(ctx) remembered at each site.

Source

pub fn internal(ctx: &Context) -> Self

A 500 that says nothing.

The detail is dropped by ErrorCode::is_sanitized, so the cause has to be logged separately; the correlation id is what connects the two.

Source

pub fn invalid( ctx: &Context, detail: impl Into<String>, pointer: impl Into<String>, ) -> Self

A 422 pointing at one member of the request document.

Source

pub fn new(code: ErrorCode) -> Self

Source

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

Attach client-facing detail.

Ignored for codes that must be sanitized — an internal error’s message can carry a connection string, so this cannot become a leak by accident at a call site.

Source

pub fn attribute(self, field: &str) -> Self

Point at the offending attribute.

A dotted field name becomes a nested JSON pointer: address.city → /data/attributes/address/city.

Source

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

Point at any member by JSON pointer, e.g. /data/relationships/owner/data.

Self::attribute covers the common case; this is for members outside /data/attributes, which relationships and the document envelope both are.

Source

pub fn parameter(self, param: impl Into<String>) -> Self

Point at the offending query parameter, e.g. sort.

Source

pub fn translate(self, translation: Translation) -> Self

Attach a translation key, so a client can render this failure in its own language.

The detail stays as it is — it is the fallback for a client with no catalog — and the key travels beside it under the error object’s meta.i18n. See i18n for why the server sends a key rather than translated prose.

use ash_jsonapi::i18n::Translation;
use ash_jsonapi::{Context, ErrorCode, JsonApiError};

let err = JsonApiError::in_request(ErrorCode::InvalidAttribute, &ctx)
    .detail("must be 80 characters or fewer")
    .attribute("name")
    .translate(Translation::new("todo.name.too_long").param("max", 80));

let meta = err.to_object().meta.unwrap();
assert_eq!(meta["i18n"]["key"], "todo.name.too_long");

Unlike detail, a key is kept on a sanitized code: it names a message this crate chose, not the underlying cause, so it cannot leak what is_sanitized exists to withhold.

Source

pub fn translation(&self) -> Option<&Translation>

The translation key attached to this error, if any.

Source

pub fn correlation_id(self, id: impl Into<String>) -> Self

Set the correlation id — what makes “here is my error id” resolvable in the audit log.

Source

pub fn in_context(self, ctx: &Context) -> Self

Take the correlation id from the request’s Context.

The normal way to build an error in a handler: the id is already in the context, so it never has to be passed separately or remembered.

Source

pub fn locale(&self) -> Option<&Locale>

The locale this error was built in, if the request named one.

Source

pub fn status(&self) -> StatusCode

The HTTP status to respond with.

Source

pub fn to_object(&self) -> ErrorObject

Render the JSON:API error object.

Trait Implementations§

Source§

impl Clone for JsonApiError

Source§

fn clone(&self) -> Self

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 Debug for JsonApiError

Source§

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

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

impl Display for JsonApiError

Source§

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

The title, plus the detail when there is one the client may see.

A sanitized code has no detail to show, so it prints its title alone — the same text the client receives, which keeps a log line and a response consistent about what was said.

Source§

impl Error for JsonApiError

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<JsonApiError> for Errors

Available on crate feature http only.
Source§

fn from(error: JsonApiError) -> Self

Converts to this type from the input type.
Source§

impl IntoResponse for JsonApiError

Available on crate feature http only.

An error is a response: return err.into() from any handler.

Source§

fn into_response(self) -> Response

Create a 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> 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<B> FromRef<B> for B
where B: Clone,

Source§

fn from_ref(backend: &B) -> B

Extract a Self from a reference to the composite backend B.
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, S> Handler<IntoResponseHandler, S> for T
where T: IntoResponse + Clone + Send + Sync + 'static,

Source§

type Future = Ready<Response<Body>>

The type of future calling this handler returns.
Source§

fn call( self, _req: Request<Body>, _state: S, ) -> <T as Handler<IntoResponseHandler, S>>::Future

Call the handler with the given request.
Source§

fn layer<L>(self, layer: L) -> Layered<L, Self, T, S>
where L: Layer<HandlerService<Self, T, S>> + Clone, <L as Layer<HandlerService<Self, T, S>>>::Service: Service<Request<Body>>,

Apply a tower::Layer to the handler. Read more
Source§

fn with_state(self, state: S) -> HandlerService<Self, T, S>

Convert the handler into a Service by providing the state
Source§

impl<H, T> HandlerWithoutStateExt<T> for H
where H: Handler<T, ()>,

Source§

fn into_service(self) -> HandlerService<H, T, ()>

Convert the handler into a Service and no state.
Source§

fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, ()>>

Convert the handler into a MakeService and no state. Read more
Source§

fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, ()>, C>

Available on crate feature tokio only.
Convert the handler into a MakeService which stores information about the incoming connection and has no state. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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

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