Skip to main content

Errors

Struct Errors 

Source
pub struct Errors { /* private fields */ }
Expand description

How the application reports and renders errors. You configure it with ApplicationBuilder::with_errors, and service providers configure it with Registrar::errors.

Later registrations take precedence. The application’s registrations run after every provider’s, so they replace a package’s status or renderer for a type.

By default, the error handler logs server errors. Errors render as JSON for requests that expect JSON, and as an HTML page otherwise, with full details when APP_DEBUG is on.

use laravel::errors::Errors;
use laravel::http::{IntoResponse, StatusCode};

#[derive(Debug)]
struct PaymentFailed;

impl std::fmt::Display for PaymentFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("The payment failed")
    }
}

impl std::error::Error for PaymentFailed {}

fn configure(errors: &mut Errors) {
    errors
        .status::<PaymentFailed>(StatusCode::PAYMENT_REQUIRED)
        .render(|_: &PaymentFailed, _request, status| {
            Some((status, "Please update your card"))
        });
}

Implementations§

Source§

impl Errors

Source

pub fn status<E>(&mut self, status: impl IntoStatusCode) -> &mut Errors
where E: Error + Send + Sync + 'static,

Respond to errors of a type with a status, as a number or a StatusCode, when ? converts them. A status given when the error is created, such as with Error::new, takes precedence. Errors with a client status, such as a 402, are expected outcomes. Laravel doesn’t report them, and they never get the debug page.

fn configure(errors: &mut Errors) {
    errors.status::<PaymentFailed>(402);
}
§Panics

Panics when the number isn’t a valid status code.

Source

pub fn render<E, R>( &mut self, render: impl Fn(&E, &Request, StatusCode) -> Option<R> + Send + Sync + 'static, ) -> &mut Errors
where E: Error + Send + Sync + 'static, R: IntoResponse,

Render errors of a type with the given function, instead of the default rendering. The function receives the error, the request, and the error’s status. It returns a response, or None to fall back to the next renderer for the type and then to the default rendering.

The error handler sends the response as it is, so give the response the status, and render JSON when the request expects it. If your application uses Inertia, render a page with request.inertia()?.render(..).

fn configure(errors: &mut Errors) {
    errors.status::<CardDeclined>(402).render(|error: &CardDeclined, request, status| {
        if request.expects_json() {
            let body = Json(serde_json::json!({ "message": error.to_string() }));

            return Some((status, body).into_response());
        }

        Some((status, "Please use another card").into_response())
    });
}

The error handler tries the renderers registered later first, so the application’s renderers replace a package’s.

Source

pub fn report<E>( &mut self, report: impl Fn(&E) + Send + Sync + 'static, ) -> &mut Errors
where E: Error + Send + Sync + 'static,

Report errors of a type with the given function, such as to an error tracker, in addition to logging them. The function receives only failures, which are errors with a 5xx status. Errors with a client status, such as a 404, are expected outcomes, so Laravel doesn’t report them.

A reporter that panics doesn’t stop the request. The error handler logs the panic and still sends the error response.

Source

pub fn report_all( &mut self, report: impl Fn(&Error) + Send + Sync + 'static, ) -> &mut Errors

Report every failure with the given function, whatever the error’s type. As with report, a reporter that panics doesn’t stop the request.

Laravel also logs failures at the error level, with the request’s context. A tracing layer added with with_logging, such as Sentry’s, therefore receives them without a reporter.

Source

pub fn dont_report<E>(&mut self) -> &mut Errors
where E: Error + Send + Sync + 'static,

Never report errors of a type. The error handler neither logs them nor passes them to the reporters, but they still render as usual.

Source

pub fn dont_flash<I, S>(&mut self, fields: I) -> &mut Errors
where I: IntoIterator<Item = S>, S: Into<String>,

Never flash these input fields, named by dot-notation path, as old input. Laravel never flashes password, password_confirmation, or current_password either. The list applies when an invalid browser form redirects back, and to Redirect::with_input.

fn configure(errors: &mut Errors) {
    errors.dont_flash(["ssn", "card.cvc"]);
}
Source

pub fn respond( &mut self, respond: impl Fn(Response, &Error, &Request) -> Response + Send + Sync + 'static, ) -> &mut Errors

Adjust every rendered error response, such as to render error pages with Inertia. The function receives the response, the error, and the request, and returns the response to send. The functions run in the order you register them, and each receives the previous function’s response.

fn configure(errors: &mut Errors) {
    errors.respond(|response, _error, _request| {
        response.with_header("cache-control", "no-store")
    });
}

Trait Implementations§

Source§

impl Clone for Errors

Source§

fn clone(&self) -> Errors

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 Errors

Source§

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

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

impl Default for Errors

Source§

fn default() -> Errors

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Errors

§

impl !UnwindSafe for Errors

§

impl Forget for Errors

§

impl Freeze for Errors

§

impl Move for Errors

§

impl Send for Errors
where RawVecInner: Send, NonZero<u16>: Send, Arc<dyn Fn(&Error, &Request, StatusCode) -> Option<Response<Body>> + Sync + Send>: Send, Arc<dyn Fn(&Error) + Sync + Send>: Send, Arc<dyn Fn(Response, &Error, &Request) -> Response + Sync + Send>: Send,

§

impl Sync for Errors
where RawVecInner: Sync, NonZero<u16>: Sync, Arc<dyn Fn(&Error, &Request, StatusCode) -> Option<Response<Body>> + Sync + Send>: Sync, Arc<dyn Fn(&Error) + Sync + Send>: Sync, Arc<dyn Fn(Response, &Error, &Request) -> Response + Sync + Send>: Sync,

§

impl Unpin for Errors

§

impl UnsafeUnpin for Errors

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> FillValue<Option<T>> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<Option<T>, Error>

Resolves the column’s value. Read more
Source§

impl<T> FillValue<T> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<T, Error>

Resolves the column’s value. Read more
Source§

impl<K> ForeignKey<K> for K

Source§

fn key(&self) -> Option<&K>

Returns the key, or None when the field holds no key.
Source§

fn __from_key(key: K) -> K

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

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T, N> NotifiedBy<T> for N
where T: Notification<N>,

Source§

fn __routes(&self) -> Vec<Route>

Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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, 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, V> UpdateValue<T> for V
where V: FillValue<T>,

Source§

fn __update<M, U>(self, column: Column<M, T>, update: U) -> U
where M: Model, U: Updates<M>, T: IntoExpr + Clone + Send + Sync + 'static,

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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