Skip to main content

Error

Struct Error 

Source
pub struct Error(/* private fields */);
Expand description

An error that handlers and middleware can return.

Any error type converts into an Error with ?, including anyhow::Error. A converted error responds with a 500 Internal Server Error, unless the application maps its type to a status or the type derives one. Context added with ErrorContext shows on the debug page and in the logs while keeping the original error’s type:

use laravel::prelude::*;

async fn license() -> laravel::Result<String> {
    let license = tokio::fs::read_to_string("license.txt")
        .await
        .context("the license can't be read")?;

    Ok(license)
}

abort and the related helpers create HTTP errors with other statuses. The application’s error handler reports and renders every error.

An error does nothing until it’s returned. A laravel::abort(403); statement on its own doesn’t stop the handler, so the compiler warns about it. The abort! macro returns the error for you:

ⓘ
#![deny(unused_must_use)]

fn update(authorized: bool) -> laravel::Result<()> {
    if !authorized {
        laravel::abort(403); // Use `laravel::abort!(403);` to return the error...
    }

    Ok(())
}

Implementations§

Source§

impl Error

Source

pub fn new<E>(status: impl IntoStatusCode, error: E) -> Error
where E: Into<Error>,

Wraps an error and gives it a status, as a number or a StatusCode, such as Error::new(402, PaymentFailed).

§Panics

Panics when the number isn’t a status code.

Source

pub fn msg(message: impl Into<String>) -> Error

Creates a 500 error whose message is for developers, such as Error::msg("the import file has no header row").

The error is a failure, so the error handler reports it. Outside debug mode, responses leave the message out. To show a message to the application’s users, use abort_with.

fn header(lines: &[&str]) -> laravel::Result<String> {
    let Some(header) = lines.first() else {
        return Err(laravel::Error::msg("the import file has no header row"));
    };

    Ok(header.to_string())
}

let error = header(&[]).unwrap_err();

assert_eq!(error.status(), 500);
assert_eq!(error.to_string(), "the import file has no header row");
Source

pub fn with_header<K, V>(self, name: K, value: V) -> Error

Adds a header to the error’s response, such as Retry-After on a 429 or WWW-Authenticate on a 401:

use laravel::http::header;

return Err(laravel::abort(429).with_header(header::RETRY_AFTER, "60"));

The response includes the header however the error is rendered, unless the response already has a header with that name.

If the name or value isn’t valid in a header, the response leaves the header out and Laravel logs a warning. The error keeps its status either way.

Source

pub fn status(&self) -> StatusCode

Returns the error’s status.

This is the status that abort or Error::new gave the error. If the error wasn’t given one, it’s the status its type derives with #[status(..)], and otherwise 500.

If the error wasn’t given a status and the application maps its type to one, the response uses the mapped status instead of the one status returns.

Source

pub fn type_name(&self) -> &'static str

Returns the name of the type the error had when it converted into an Error, for diagnostics.

An error from anyhow is an anyhow::Error. As with std::any::type_name, the exact spelling can change between Rust versions, so use is to check the type.

Source

pub fn is<E>(&self) -> bool
where E: Error + Send + Sync + 'static,

Returns whether the error is of type E.

Context added with anyhow doesn’t hide the type, so an io::Error with context is still an io::Error.

Source

pub fn downcast_ref<E>(&self) -> Option<&E>
where E: Error + Send + Sync + 'static,

Returns the error as type E, or None when it’s another type.

Like is, it looks through context added with anyhow.

Source

pub fn chain(&self) -> impl Iterator<Item = &(dyn Error + 'static)>

Returns the error and the errors that caused it, outermost first, starting with any context.

Source

pub fn context(self, context: impl Display) -> Error

Adds a message that says what the application was doing when the error happened, for the logs and the developer.

The context becomes the error’s message, and the earlier message becomes its cause:

async fn invoice(id: u64) -> laravel::Result<String> {
    let invoice = find(id)
        .await
        .map_err(|error| error.context(format!("the invoice `{id}` can't be loaded")))?;

    Ok(invoice)
}

The error keeps its type for is, its status, its headers, its causes, and its location.

Responses leave the context out. A client error, such as a 404, shows the message of the error that set its status. A server error shows the context only on the debug page.

Source

pub fn location(&self) -> Option<&'static Location<'static>>

Returns where the error originated: the ? that converted it, or the call to abort or Error::new.

An error that a framework call returns, such as reading a file from a disk or running a process, points to that call, even when the call is async. An error from a view that fails to render points to where the view was created, and an error for a missing handler dependency points to the route’s registration. Unlike a backtrace, the location costs nothing to keep. An error from a handler’s panic has no location, because the panic message already says where it happened.

Source

pub fn backtrace(&self) -> Option<&Backtrace>

Returns the backtrace captured where the wrapped error was created.

It returns None unless the RUST_BACKTRACE or RUST_LIB_BACKTRACE environment variable enables backtraces.

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Error

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 Error

Source§

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

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

impl Display for Error

Source§

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

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

impl<E> From<E> for Error
where E: Into<Error>,

Anything that converts into anyhow::Error converts with ?. That includes every error type and anyhow::Error itself.

Source§

fn from(error: E) -> Error

Converts to this type from the input type.
Source§

impl From<Error> for Box<dyn Error + Sync + Send>

An error boxed for a library that takes any error, such as a fallible Inertia prop. Unboxing the error restores it whole, with its status, headers, and location.

Source§

fn from(error: Error) -> Box<dyn Error + Sync + Send>

Converts to this type from the input type.
Source§

impl From<ValidationError> for Error

Source§

fn from(error: ValidationError) -> Error

Converts to this type from the input type.
Source§

impl IntoResponse for Error

Source§

fn into_response(self) -> Response

Turn this into a Response. Read more
Send a cookie with this response, replacing any cookie the response already sends with the same name, path, and domain. Read more
Remove a browser cookie. Pass the cookie’s name, or a Cookie with the path and domain that set it. Read more
Source§

fn with_header<K, V>(self, name: K, value: V) -> Response

Send a header with the response, replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.
Source§

fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> Response

Send several headers with the response, each replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.
Source§

impl IntoResponse for Error

Returning an error from a handler responds with its status. The error boundary around the handler then reports and renders the error.

Source§

fn into_response(self) -> Response<Body>

Create a response.

Auto Trait Implementations§

§

impl Forget for Error

§

impl Freeze for Error
where *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze,

§

impl Move for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error
where Arc<Inner>: Send,

§

impl Sync for Error
where Arc<Inner>: Sync,

§

impl Unpin for Error
where Arc<Inner>: Unpin,

§

impl UnsafeUnpin for Error
where *const ArcInner<Inner> is !null: UnsafeUnpin, PhantomData<ArcInner<Inner>>: UnsafeUnpin,

§

impl UnwindSafe for Error
where Arc<Inner>: UnwindSafe,

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

Convert the handler into a MakeService which stores information about the incoming connection and has no state. 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<T> IntoMarkdown for T
where T: Display,

Source§

fn into_markdown(self) -> Markdown

The value as Slack markdown.
Source§

fn __format(self, format: impl FnOnce(&dyn Display) -> String) -> Markdown

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