Error Handling
- Introduction
- Debug mode
- Returning errors
- HTTP errors
- Invalid input
- Failures and expected outcomes
- Error pages
- Customizing the error handler
- Testing errors
Introduction
When you create a new Laravel project, error handling is already configured for you. Whenever a handler returns an error, such as when a requested post doesn't exist or a database query fails, Laravel converts it into an HTTP response: JSON for API clients and an error page for browsers. When an error is a server failure, Laravel also logs it so you can investigate what went wrong.
Whenever you need to customize how your application reports or renders errors, configure the error handler with with_errors in src/app.rs.
Debug mode
The APP_DEBUG environment variable controls how much detail Laravel exposes when a server failure occurs. When APP_DEBUG=true, browsers receive a detailed debug page showing the error, where it happened, its chain of causes, and the incoming request, while JSON responses include the error's type, file, and line.
When APP_DEBUG=false, Laravel replaces failure messages with "Server Error" so internal messages written for your logs never leak to users. The only exception is a failure raised intentionally for clients with abort_with, such as laravel::abort_with(503, "We're upgrading. Back in a minute."), which includes that message in JSON responses.
New applications enable debug mode in .env for local development:
1APP_DEBUG=true1APP_DEBUG=true
Always set APP_DEBUG to false in production. The debug page exposes stack traces, request data, and internal error messages to your users.
Returning errors
Handlers and middleware that can fail return laravel::Result. Using ?, any type that implements std::error::Error converts automatically into laravel::Error, as does an anyhow::Error from a library. Unless the error specifies a status code, Laravel responds with 500 Internal Server Error:
1use laravel::prelude::*;23use crate::models::User;45pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {6 let user = User::find_or_fail(id).await?;78 Ok(Json(user))9}1use laravel::prelude::*;23use crate::models::User;45pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {6 let user = User::find_or_fail(id).await?;78 Ok(Json(user))9}
If the database query fails, find_or_fail returns a 500 error. If no user matches the given ID, it returns a 404 because ModelNotFound carries a status of 404.
When you want to return a one-off error without defining a custom error type, create one from a message with laravel::Error::msg:
1pub fn header_row(contents: &str) -> laravel::Result<&str> {2 let Some(header) = contents.lines().next() else {3 return Err(laravel::Error::msg("the import file has no header row"));4 };56 Ok(header)7}1pub fn header_row(contents: &str) -> laravel::Result<&str> {2 let Some(header) = contents.lines().next() else {3 return Err(laravel::Error::msg("the import file has no header row"));4 };56 Ok(header)7}
Laravel treats this error as a 500 failure, logging the message while showing "Server Error" to users outside debug mode. If you want the message returned to the client instead, use laravel::abort_with(500, message).
Defining your own errors
An error type is any struct or enum that implements std::error::Error. New applications include the thiserror crate, which derives the implementation for you. The #[error("...")] attribute defines the error's message and may interpolate fields by name or position:
1#[derive(Debug, thiserror::Error)]2pub enum PaymentError {3 #[error("The card was declined: {reason}")]4 Declined { reason: String },56 #[error("The amount {0} is below the minimum")]7 BelowMinimum(u64),89 #[error("The receipt couldn't be saved")]10 Receipt(#[from] std::io::Error),11}1#[derive(Debug, thiserror::Error)]2pub enum PaymentError {3 #[error("The card was declined: {reason}")]4 Declined { reason: String },56 #[error("The amount {0} is below the minimum")]7 BelowMinimum(u64),89 #[error("The receipt couldn't be saved")]10 Receipt(#[from] std::io::Error),11}
Adding #[from] lets ? convert the inner error into your variant automatically, so an std::io::Error becomes PaymentError::Receipt and keeps the original io::Error as its cause:
1pub fn save_receipt(path: &str, contents: &str) -> Result<(), PaymentError> {2 std::fs::write(path, contents)?;34 Ok(())5}1pub fn save_receipt(path: &str, contents: &str) -> Result<(), PaymentError> {2 std::fs::write(path, contents)?;34 Ok(())5}
Errors with their own status
To associate an HTTP status code with an error type, such as 409 Conflict for a double booking, derive Status and add #[status(..)]. Returning that error from a handler with ? then responds with that status:
1use laravel::errors::Status;23#[derive(Debug, thiserror::Error, Status)]4#[error("This time slot is already booked")]5#[status(409)]6pub struct BookingConflict;1use laravel::errors::Status;23#[derive(Debug, thiserror::Error, Status)]4#[error("This time slot is already booked")]5#[status(409)]6pub struct BookingConflict;
On an enum, you may give each variant its own status. Any variant without a #[status(..)] attribute defaults to 500:
1use laravel::errors::Status;23#[derive(Debug, thiserror::Error, Status)]4pub enum PaymentError {5 #[error("The card was declined: {reason}")]6 #[status(402)]7 Declined { reason: String },89 #[error("The amount {0} is below the minimum")]10 #[status(422)]11 BelowMinimum(u64),1213 #[error("The receipt couldn't be saved")]14 Receipt(#[from] std::io::Error),15}1use laravel::errors::Status;23#[derive(Debug, thiserror::Error, Status)]4pub enum PaymentError {5 #[error("The card was declined: {reason}")]6 #[status(402)]7 Declined { reason: String },89 #[error("The amount {0} is below the minimum")]10 #[status(422)]11 BelowMinimum(u64),1213 #[error("The receipt couldn't be saved")]14 Receipt(#[from] std::io::Error),15}
The status may be a numeric code such as 402 or a StatusCode constant such as StatusCode::PAYMENT_REQUIRED.
You can't derive Status on an error type defined in another crate. Instead, map its status inside with_errors in src/app.rs. Mapping a type there also overrides a derived status, such as one from a package:
1use laravel::prelude::*;23Application::configure()4 .with_errors(|errors, _| {5 errors.status::<laravel::db::sqlx::Error>(503);6 })1use laravel::prelude::*;23Application::configure()4 .with_errors(|errors, _| {5 errors.status::<laravel::db::sqlx::Error>(503);6 })
To assign a status to a single error at the point you return it, wrap it with laravel::Error::new:
1return Err(laravel::Error::new(409, BookingConflict));1return Err(laravel::Error::new(409, BookingConflict));
Adding context
Low-level errors such as "No such file or directory" rarely explain what your application was doing when they happened. To attach context for your logs, call context or with_context on any Result. The ErrorContext trait is included in the prelude:
1use laravel::prelude::*;23let license = tokio::fs::read_to_string("license.txt")4 .await5 .context("the license can't be read")?;67let post = Post::find_or_fail(id)8 .await9 .with_context(|| format!("the post `{id}` can't be loaded"))?;1use laravel::prelude::*;23let license = tokio::fs::read_to_string("license.txt")4 .await5 .context("the license can't be read")?;67let post = Post::find_or_fail(id)8 .await9 .with_context(|| format!("the post `{id}` can't be loaded"))?;
The context becomes the outer message and the original error becomes its cause, so your logs read the post `42` can't be loaded: no such table: posts. The error keeps its original type, caller location, and status code, so a 404 with context is still a 404 and JSON logs still report the underlying error type rather than anyhow::Error.
Context is meant for developers, not end users. Laravel logs and reports it and displays it on the debug page, but omits it from normal responses so you can safely include IDs or tenant names. A 404 with context still responds with "Not Found". To customize the message users see, customize your error pages.
HTTP errors
Sometimes a handler needs to stop and return an HTTP status directly, such as 404 Not Found or 403 Forbidden. The abort! macro returns from the handler immediately using the status code and optional message you provide. For example, if your User model has a banned field, this handler hides profiles of banned users:
1use laravel::prelude::*;23use crate::models::User;45pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {6 let user = User::find_or_fail(id).await?;78 if user.banned {9 laravel::abort!(404);10 }1112 Ok(Json(user))13}1use laravel::prelude::*;23use crate::models::User;45pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {6 let user = User::find_or_fail(id).await?;78 if user.banned {9 laravel::abort!(404);10 }1112 Ok(Json(user))13}
The status may be a number or a StatusCode, and the optional message accepts format! arguments:
1laravel::abort!(StatusCode::FORBIDDEN);23laravel::abort!(409, "The name `{}` is taken.", user.name);1laravel::abort!(StatusCode::FORBIDDEN);23laravel::abort!(409, "The name `{}` is taken.", user.name);
To turn an Option::None into an HTTP error, call or_abort. Its OrAbort trait is included in the prelude:
1let user = User::find(id).await?.or_abort(404)?;1let user = User::find(id).await?.or_abort(404)?;
Aborting when a condition holds
You may abort conditionally with abort_if (which fails when the condition is true) and abort_unless (which fails when it's false). For example, if your Post model has a user_id field, this handler allows only the post's author to edit it:
1use laravel::prelude::*;2use laravel::view::View;34use crate::models::{Post, User};56pub async fn edit(7 user: Authenticated<User>,8 Params(id): Params<i64>,9) -> laravel::Result<View> {10 let post = Post::find_or_fail(id).await?;1112 laravel::abort_if(post.user_id != user.id, 403)?;1314 Ok(view("posts.edit", data! { post }))15}1use laravel::prelude::*;2use laravel::view::View;34use crate::models::{Post, User};56pub async fn edit(7 user: Authenticated<User>,8 Params(id): Params<i64>,9) -> laravel::Result<View> {10 let post = Post::find_or_fail(id).await?;1112 laravel::abort_if(post.user_id != user.id, 403)?;1314 Ok(view("posts.edit", data! { post }))15}
For reusable permission checks across multiple handlers, a policy is usually clearer than repeating conditions in each handler.
Headers
Any error may carry response headers, such as Retry-After on a 429 Too Many Requests response, and Laravel includes them whether the error renders as JSON or HTML. The abort and abort_with functions build an Error without returning it immediately, so you may attach headers before returning:
1return Err(laravel::abort(429).with_header("retry-after", "60"));1return Err(laravel::abort(429).with_header("retry-after", "60"));
Invalid input
Validation rules catch most invalid input before your handler runs. When your handler discovers a problem that rules can't express, such as an email address that has already been invited, return an InvalidInput error with a message for each invalid field using the invalid! macro:
1use laravel::validation::invalid;23invalid!(email => "That email is already invited.");1use laravel::validation::invalid;23invalid!(email => "That email is already invited.");
Laravel treats InvalidInput as a failed validation. For browser form submissions, Laravel redirects back to the form with the errors and old input. For API requests, Laravel responds with 422 Unprocessable Content and a JSON payload listing each field's errors:
1{2 "message": "That email is already invited.",3 "errors": {4 "email": ["That email is already invited."]5 }6}1{2 "message": "That email is already invited.",3 "errors": {4 "email": ["That email is already invited."]5 }6}
To learn more about defining validation rules and returning validation errors, check out the validation guide.
Failures and expected outcomes
Laravel handles errors differently depending on their HTTP status code:
- Failures have a
5xxserver status, such as500or503. Laravel reports them by logging the error and passing it to your reporters, and hides their internal message from users unless you raised the error withabort_with. - Expected outcomes have any non-
5xxstatus, usually a4xxclient status such as404,403, or422. Laravel doesn't report them. JSON responses include the error's message, while HTML error pages display its status.
Reporting and carrying on
Sometimes a failure shouldn't break the entire request. For example, a product page can still render without its recommendations, even though you want to know that the recommendation service is down. Call laravel::report to log and report the error while your handler continues.
This handler fetches recommendations with the HTTP client. If the request fails, it reports the error and renders the page with an empty list:
1use laravel::http::client;2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(Params(id): Params<i64>) -> laravel::Result<View> {8 let product = Product::find_or_fail(id).await?;910 let recommendations = client::get(format!(11 "https://recommendations.example.com/products/{id}",12 ))13 .ensure_successful()14 .await15 .and_then(|response| response.json::<Vec<serde_json::Value>>())16 .unwrap_or_else(|error| {17 laravel::report(error);1819 Vec::new()20 });2122 Ok(view("products.show", data! { product, recommendations }))23}1use laravel::http::client;2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(Params(id): Params<i64>) -> laravel::Result<View> {8 let product = Product::find_or_fail(id).await?;910 let recommendations = client::get(format!(11 "https://recommendations.example.com/products/{id}",12 ))13 .ensure_successful()14 .await15 .and_then(|response| response.json::<Vec<serde_json::Value>>())16 .unwrap_or_else(|error| {17 laravel::report(error);1819 Vec::new()20 });2122 Ok(view("products.show", data! { product, recommendations }))23}
laravel::report logs the error with the request's context and passes it to your reporters. It skips expected outcomes, so laravel::report(laravel::abort(404)) does nothing.
Panics
If a handler panics, Laravel catches the panic, logs the file and line where it happened, and renders a 500 response while your application continues serving other requests. Even so, return Result errors for failures you anticipate and reserve panics for bugs.
Error pages
Requests that want JSON, along with every request to a route in the api group, receive errors as JSON, such as { "message": "Not Found" }. All other requests receive an HTML error page.
In JSON responses, "message" comes from the error that set the status code, whether passed to abort! or abort_with, or defined with #[error("...")] on an error type that derives Status:
1laravel::abort!(404, "That post doesn't exist.");1laravel::abort!(404, "That post doesn't exist.");
For example, returning BookingConflict (409) produces "This time slot is already booked", even if you attached internal context. A missing model produces ModelNotFound's message naming the model and key, while server failures return "Server Error" unless debug mode is enabled or you used abort_with.
HTML error pages display the status code and reason phrase, such as "404 Not Found" or "419 Page Expired", whether debug mode is on or off. A 403 page displays the error's message instead so a policy's denial can explain why access was refused. When debug mode is on, server failures render the debug page instead.
To customize your error pages, create a view named after the status code, such as resources/views/errors/404.html. You may also create fallback views at errors/4xx.html and errors/5xx.html for any status without a dedicated view. Each view receives status and message:
1{% extends "layouts.app" %}23{% block content %}4 <h1>{{ status }}</h1>5 <p>{{ message }}</p>6{% endblock %}1{% extends "layouts.app" %}23{% block content %}4 <h1>{{ status }}</h1>5 <p>{{ message }}</p>6{% endblock %}
If your application uses Inertia, you may render errors with a frontend page component instead. Return the component's name from your HandleInertiaRequests middleware's error_page method. The component receives an error prop holding status and message, along with your shared props. New applications include an Error page component you can customize:
1use laravel::inertia;23impl inertia::Middleware for HandleInertiaRequests {4 fn error_page(&self) -> Option<&str> {5 Some("Error")6 }7}1use laravel::inertia;23impl inertia::Middleware for HandleInertiaRequests {4 fn error_page(&self) -> Option<&str> {5 Some("Error")6 }7}
To learn more about setting titles and other metadata on error pages, check out the head metadata guide's section on error pages.
Customizing the error handler
To customize how your application reports and renders errors, call with_errors in src/app.rs. Its closure receives the Errors builder and your application's configuration, so you may conditionally register reporters when an error tracker's key is configured:
1use laravel::prelude::*;23Application::configure()4 .with_errors(|errors, config| {5 // ...6 })1use laravel::prelude::*;23Application::configure()4 .with_errors(|errors, config| {5 // ...6 })
Reporting errors
Laravel logs every server failure automatically. To also send failures of a specific type to an external service, register a reporter for that type inside with_errors:
1errors.report(|error: &PaymentError| {2 // Send the error to your error tracker...3});1errors.report(|error: &PaymentError| {2 // Send the error to your error tracker...3});
To report every failure regardless of its type, use report_all. Its closure receives laravel::Error, which you may inspect:
1errors.report_all(|error| {2 // Send every failure to your error tracker...3});1errors.report_all(|error| {2 // Send every failure to your error tracker...3});
If your error tracker integrates with tracing, such as Sentry, you don't need a custom reporter. Laravel logs every failure at the error level, so adding the tracker's tracing layer captures them automatically.
Ignoring errors by type
To keep expected failures out of your logs and reporters, ignore their type with dont_report. For example, an application that already retries failed calls to a partner API might ignore HTTP client errors:
1use laravel::http::client;23errors.dont_report::<client::Error>();1use laravel::http::client;23errors.dont_report::<client::Error>();
Ignored errors still render responses as usual.
Rendering errors
To render a specific error type your own way, register a renderer with render. Your closure receives the error, the request, and the error's status code, and returns Option<Response>. Returning None falls back to Laravel's default rendering.
Laravel sends whatever response your renderer returns, so include the status code or the response will be 200 OK. Check request.wants_json() when your renderer serves both API clients and browsers. For example, this renderer returns the decline reason as JSON for API clients and renders an Inertia page for browsers:
1use laravel::inertia::props;2use serde_json::json;34errors.render(|error: &PaymentError, request, status| {5 let PaymentError::Declined { reason } = error else {6 return None;7 };89 if request.wants_json() {10 let body = json!({11 "message": error.to_string(),12 "reason": reason,13 });1415 return Some((status, Json(body)).into_response());16 }1718 let page = request19 .inertia()?20 .render("Billing/CardDeclined", props! { reason => reason });2122 Some((status, page).into_response())23});1use laravel::inertia::props;2use serde_json::json;34errors.render(|error: &PaymentError, request, status| {5 let PaymentError::Declined { reason } = error else {6 return None;7 };89 if request.wants_json() {10 let body = json!({11 "message": error.to_string(),12 "reason": reason,13 });1415 return Some((status, Json(body)).into_response());16 }1718 let page = request19 .inertia()?20 .render("Billing/CardDeclined", props! { reason => reason });2122 Some((status, page).into_response())23});
Adjusting every error response
To modify every rendered error response, register a callback with respond. It receives the rendered Response, the error, and the request, and returns the response to send. For example, this responder prevents browsers and proxies from caching error pages:
1errors.respond(|response, _error, _request| {2 response.with_header("cache-control", "no-store")3});1errors.respond(|response, _error, _request| {2 response.with_header("cache-control", "no-store")3});
If your application uses Inertia, you may also use respond to redirect users back to their form with a message when a 419 page-expired error occurs. To learn more, check out the Inertia guide's section on expired pages.
Keeping input out of old input
When an invalid form redirects back, Laravel flashes the submitted fields to the session as old input. Laravel never flashes password, password_confirmation, or current_password. To exclude additional sensitive fields, list them with dont_flash, using "dot" notation for nested fields:
1errors.dont_flash(["ssn", "card.number", "card.cvc"]);1errors.dont_flash(["ssn", "card.number", "card.cvc"]);
Errors from packages
Packages configure their own errors through app.errors() in their service provider's register method, using the same Errors builder as with_errors. Your application's with_errors runs after every service provider, so your status mappings override a package's for the same error type, and your renderers run first (returning None falls back to the package's renderer). To learn more about registering errors in a package, check out the package development guide's section on errors.
Inspecting errors
Inside reporters, responders, and tests, you may inspect a laravel::Error with these methods:
| Method | Returns |
|---|---|
status() |
Its status code, such as StatusCode::PAYMENT_REQUIRED. |
is::<PaymentError>() |
Whether it's a PaymentError. |
downcast_ref::<PaymentError>() |
The underlying PaymentError, if it is one. |
chain() |
Its context messages, followed by the error and its causes. |
location() |
Where it was created, such as src/http/handlers/orders.rs:42:31. |
Testing errors
In HTTP tests, each response retains the error it was rendered from, so you may assert directly on error types rather than matching HTML text. Use assert_error to check the rendered error's type, assert_reported and assert_not_reported to check whether a specific error type was reported (including via laravel::report), and assert_nothing_reported to verify that no failures were reported at all:
1use laravel::http::client;2use laravel::model::create;3use laravel::testing::prelude::*;45use crate::models::Product;67#[laravel::test]8async fn a_declined_card_is_a_payment_error(app: Application) {9 app.post("/checkout")10 .await11 .assert_payment_required()12 .assert_error::<PaymentError>()13 .assert_nothing_reported();14}1516#[laravel::test]17async fn products_show_without_recommendations(app: Application) -> laravel::Result<()> {18 let product = create!(Product { name: "Desk lamp" }).await?;1920 let _http = client::fake()21 .with("recommendations.example.com/*", client::failed_connection());2223 app.get(format!("/products/{}", product.id))24 .await25 .assert_ok()26 .assert_reported::<client::Error>();2728 Ok(())29}1use laravel::http::client;2use laravel::model::create;3use laravel::testing::prelude::*;45use crate::models::Product;67#[laravel::test]8async fn a_declined_card_is_a_payment_error(app: Application) {9 app.post("/checkout")10 .await11 .assert_payment_required()12 .assert_error::<PaymentError>()13 .assert_nothing_reported();14}1516#[laravel::test]17async fn products_show_without_recommendations(app: Application) -> laravel::Result<()> {18 let product = create!(Product { name: "Desk lamp" }).await?;1920 let _http = client::fake()21 .with("recommendations.example.com/*", client::failed_connection());2223 app.get(format!("/products/{}", product.id))24 .await25 .assert_ok()26 .assert_reported::<client::Error>();2728 Ok(())29}