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
impl Error
Sourcepub fn new<E>(status: impl IntoStatusCode, error: E) -> Error
pub fn new<E>(status: impl IntoStatusCode, error: E) -> 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.
Sourcepub fn msg(message: impl Into<String>) -> Error
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");Sourcepub fn with_header<K, V>(self, name: K, value: V) -> Errorwhere
K: TryInto<HeaderName>,
<K as TryInto<HeaderName>>::Error: Debug,
V: TryInto<HeaderValue>,
<V as TryInto<HeaderValue>>::Error: Debug,
pub fn with_header<K, V>(self, name: K, value: V) -> Errorwhere
K: TryInto<HeaderName>,
<K as TryInto<HeaderName>>::Error: Debug,
V: TryInto<HeaderValue>,
<V as TryInto<HeaderValue>>::Error: Debug,
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.
Sourcepub fn status(&self) -> StatusCode
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.
Sourcepub fn type_name(&self) -> &'static str
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.
Sourcepub fn is<E>(&self) -> bool
pub fn is<E>(&self) -> bool
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.
Sourcepub fn downcast_ref<E>(&self) -> Option<&E>
pub fn downcast_ref<E>(&self) -> Option<&E>
Returns the error as type E, or None when it’s another type.
Like is, it looks through context added with anyhow.
Sourcepub fn chain(&self) -> impl Iterator<Item = &(dyn Error + 'static)>
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.
Sourcepub fn context(self, context: impl Display) -> Error
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.
Sourcepub fn location(&self) -> Option<&'static Location<'static>>
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.
Trait Implementations§
Source§impl<E> From<E> for Error
Anything that converts into anyhow::Error converts with ?. That
includes every error type and anyhow::Error itself.
impl<E> From<E> for Error
Anything that converts into anyhow::Error converts with ?. That
includes every error type and anyhow::Error itself.
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.
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§impl From<ValidationError> for Error
impl From<ValidationError> for Error
Source§fn from(error: ValidationError) -> Error
fn from(error: ValidationError) -> Error
Source§impl IntoResponse for Error
impl IntoResponse for Error
Source§fn with_header<K, V>(self, name: K, value: V) -> Response
fn with_header<K, V>(self, name: K, value: V) -> Response
500 error.Source§fn with_headers<K, V>(
self,
headers: impl IntoIterator<Item = (K, V)>,
) -> Response
fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> Response
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.
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>
fn into_response(self) -> Response<Body>
Auto Trait Implementations§
impl Forget for Error
impl Freeze for Error
impl Move for Error
impl RefUnwindSafe for Errorwhere
Atomic<usize>: RefUnwindSafe,
Error: RefUnwindSafe,
NonZero<u16>: RefUnwindSafe,
Atomic<*mut ()>: RefUnwindSafe,
impl Send for Error
impl Sync for Error
impl Unpin for Error
impl UnsafeUnpin for Error
impl UnwindSafe for Errorwhere
Arc<Inner>: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<K> ForeignKey<K> for K
impl<K> ForeignKey<K> for K
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T, S> Handler<IntoResponseHandler, S> for T
impl<T, S> Handler<IntoResponseHandler, S> for T
Source§fn call(
self,
_req: Request<Body>,
_state: S,
) -> <T as Handler<IntoResponseHandler, S>>::Future
fn call( self, _req: Request<Body>, _state: S, ) -> <T as Handler<IntoResponseHandler, S>>::Future
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>>,
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>>,
tower::Layer to the handler. Read moreSource§fn with_state(self, state: S) -> HandlerService<Self, T, S>
fn with_state(self, state: S) -> HandlerService<Self, T, S>
Service by providing the stateSource§impl<H, T> HandlerWithoutStateExt<T> for H
impl<H, T> HandlerWithoutStateExt<T> for H
Source§fn into_service(self) -> HandlerService<H, T, ()>
fn into_service(self) -> HandlerService<H, T, ()>
Service and no state.Source§fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, ()>>
fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, ()>>
MakeService and no state. Read moreSource§fn into_make_service_with_connect_info<C>(
self,
) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, ()>, C>
fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, ()>, C>
MakeService which stores information
about the incoming connection and has no state. Read moreSource§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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