跳至正文

Error Handling ​

Introduction ​

When you create a new Laravel project, error handling is already configured for you. Whenever a handler fails with an error, such as when a requested post doesn't exist or a database query fails, Laravel converts the error 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, set the Errors option in bootstrap/app.go.

Debug mode ​

The APP_DEBUG environment variable controls how much detail Laravel exposes when a server failure occurs. When APP_DEBUG=true, a failure's error page shows the error's message and its Go type, the source around the line that failed or panicked, the errors it wraps, and the request's headers and route, along with the stack for a panic. JSON responses include the type in an error key and a panic's stack in a trace key. The type is the one beneath any context you added with fmt.Errorf, so a *db.QueryError wrapped as loading post 7: %w is still shown as a *db.QueryError.

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 you raised intentionally for clients with web.Abort or web.Abortf, such as web.Abortf(http.StatusServiceUnavailable, "We're upgrading. Back in a minute."), whose message JSON responses include. Whatever the setting, Laravel logs the full error. Debug mode is off unless you turn it on, and new applications enable it in .env for local development:

ini
APP_DEBUG=true

警告

Always set APP_DEBUG to false in production. The debug page exposes stack traces and internal error messages, such as a query or a file path, to your users.

Returning errors ​

Handlers and middleware return a *web.Response. When a handler gets an error back from the code it calls, it fails with the error by returning web.Fail(err). Unless the error chooses a status code, Laravel responds with 500 Internal Server Error:

go
package users

import (
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Show(r *web.Request) *web.Response {
	user, err := model.FromRoute[models.User](r, "user")
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(user)
}

If the database query fails, model.FromRoute returns an error that responds with a 500. If no user matches the route's ID, it returns a *db.NotFoundError, which responds with a 404 because it carries a status of its own.

Only the handler turns an error into a response. The code your handlers call, such as a function in one of your own packages that a job also calls, returns an ordinary error. When you want to return a one-off error, create one with errors.New or fmt.Errorf:

go
func headerRow(contents string) (string, error) {
	header, _, _ := strings.Cut(contents, "\n")
	if header == "" {
		return "", errors.New("the import file has no header row")
	}

	return header, nil
}

When a handler fails with this error, Laravel treats it as a 500 failure, logging the message while showing "Server Error" to users outside debug mode.

Defining your own errors ​

When the code that calls yours needs to tell one failure from another, such as a declined card from a database outage, give the failure an error of its own. For a failure that needs no details, declare a sentinel error with errors.New. For a failure that carries details, such as the reason a card was declined, define a type with an Error method:

go
package billing

import "errors"

// ErrBelowMinimum means the amount is too small to charge.
var ErrBelowMinimum = errors.New("The amount is below the minimum.")

// A DeclinedError means the card issuer declined the charge.
type DeclinedError struct {
	Reason string
}

func (e *DeclinedError) Error() string {
	return "The card was declined: " + e.Reason
}

Callers check for a sentinel error with errors.Is, and for an error type with errors.As or errors.AsType. Both look through every error wrapped around the error they're looking for:

go
if declined, ok := errors.AsType[*billing.DeclinedError](err); ok {
	// Show declined.Reason to the customer...
}

Errors with their own status ​

To associate an HTTP status code with an error, such as 402 Payment Required for a declined card, give the error a StatusCode method. Every handler that fails with the error then responds with that status, without translating the error itself:

go
func (e *DeclinedError) StatusCode() int {
	return http.StatusPaymentRequired
}

A sentinel error from errors.New has no methods of its own, so a sentinel that needs a status is a value of an unexported type instead:

go
// ErrBelowMinimum means the amount is too small to charge.
var ErrBelowMinimum = belowMinimum{}

type belowMinimum struct{}

func (belowMinimum) Error() string   { return "The amount is below the minimum." }
func (belowMinimum) StatusCode() int { return http.StatusUnprocessableEntity }

An error from a library has no StatusCode method, and you can't add one. To give such an error a status at the point you return it, wrap it in a web.Error with the status and the error as its Err field. For example, this handler responds with a 503 when the search service is down:

go
results, err := search.Posts(r, filters.Query)
if err != nil {
	return web.Fail(&web.Error{Status: http.StatusServiceUnavailable, Err: err})
}

Errors that build their own response ​

Some failures always send the user to the same place. For example, when a feature requires a subscription, you might redirect a browser to the plans page and give an API client a 402. An error may build its whole response by implementing web.Responder, so every handler that fails with the error sends the same response:

go
package billing

import (
	"net/http"

	"go.laravel.com/web"
)

// ErrSubscriptionRequired sends the user to the plans page.
var ErrSubscriptionRequired = subscriptionRequired{}

type subscriptionRequired struct{}

func (subscriptionRequired) Error() string { return "A subscription is required." }

func (subscriptionRequired) Respond(r *web.Request) *web.Response {
	if r.ExpectsJSON() {
		return web.Abort(http.StatusPaymentRequired)
	}

	return web.RedirectRoute("billing.plans")
}

If your application uses Inertia, a Respond method may also render an error as a page of its own. To learn more, check out the Inertia guide's section on rendering an error as a page.

Adding context ​

Low-level errors such as connection refused rarely explain what your application was doing when they happened. To attach context for your logs, wrap the error with fmt.Errorf and %w:

go
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
	return web.Fail(fmt.Errorf("loading post %s for editing: %w", r.PathValue("post"), err))
}

The context becomes the start of the message, so your logs read loading post 42 for editing: ... followed by the original error's message. The wrapped error keeps the original error's status, so a 404 with context is still a 404, and errors.Is and errors.As still find the original error.

Context is meant for developers, not end users. Laravel logs and reports the whole message, but a response shows only the message of the error that chose the status, so you can safely include IDs or tenant names. A 404 with context still responds with "Not Found". To customize the page users see, customize your error pages.

HTTP errors ​

Sometimes a handler needs to stop and respond with an HTTP status directly, such as 404 Not Found or 403 Forbidden. web.Abort returns the error response for the status code you give it. For example, this handler allows only a post's author to delete it:

go
package posts

import (
	"net/http"

	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Destroy(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	if post.UserID != models.CurrentUser(r).ID {
		return web.Abort(http.StatusForbidden)
	}

	// Delete the post...

	return web.RedirectRoute("posts.index")
}

The user sees the status's standard text, such as "Forbidden". To show a message of your own instead, use web.Abortf, which formats the message as fmt.Errorf does:

go
return web.Abortf(http.StatusConflict, "The name %q is taken.", user.Name)

web.Abort and web.Abortf return a response, so only a handler or a middleware can return them. Code below the handler returns an error instead. For example, resolving a ticket that's already resolved is a conflict. Return web.Errorf, which takes the same status and message as web.Abortf:

go
func Resolve(ctx context.Context, ticket *models.Ticket) error {
	if ticket.Status == models.StatusResolved {
		return web.Errorf(http.StatusConflict, "Ticket #%d is already resolved.", ticket.ID)
	}

	// Resolve the ticket...

	return nil
}

The handler passes the error to web.Fail, as it would any other error, and the user gets a 409 with the message. A job that calls Resolve gets an ordinary error whose text is the message.

For reusable permission checks across multiple handlers, a policy is usually clearer than repeating conditions in each handler.

Headers ​

Any error response may carry headers, such as Retry-After on a 503 Service Unavailable response, and Laravel includes them whether the error renders as JSON or HTML. In a handler, chain WithHeader onto the response that web.Abort returns:

go
return web.Abort(http.StatusServiceUnavailable).WithHeader("Retry-After", "60")

Code below the handler returns an error rather than a response, so it puts the header on the error itself. For example, an export function might limit how often a user may export their data. Build a web.Error and set its Header field, and the handler passes the error to web.Fail as usual:

go
return &web.Error{
	Status:  http.StatusTooManyRequests,
	Message: "You've already exported your data this minute. Try again shortly.",
	Header:  http.Header{"Retry-After": {"60"}},
}

Invalid input ​

Validation rules catch most invalid input before your handler acts on it. When your handler discovers a problem that rules can't express, such as an email address that has already been invited, return web.Invalid with the field's name and its message:

go
return web.Invalid("email", "That email is already invited.")

Laravel treats this error 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:

json
{
    "message": "That email is already invited.",
    "errors": {
        "email": ["That email is already invited."]
    }
}

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 5xx server status, such as 500 or 503. Laravel reports them by logging the error and passing it to your report hook, and hides their message from users outside debug mode.
  • Expected outcomes have any other status, usually a 4xx client status such as 404, 403, or 422. Laravel doesn't report them. JSON responses include the error's message, while HTML error pages display its status.

A status you chose with web.Abort, web.Abortf, or a web.Error without an Err field isn't a fault, so Laravel doesn't report it, even a 503. When something went wrong behind the status, give the error its cause with %w or the Err field, and Laravel reports the failure with its cause.

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 r.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:

go
package products

import (
	"fmt"

	"go.laravel.com/httpclient"
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Show(r *web.Request) *web.Response {
	product, err := model.FromRoute[models.Product](r, "product")
	if err != nil {
		return web.Fail(err)
	}

	var recommendations []map[string]any

	url := fmt.Sprintf("https://recommendations.example.com/products/%d", product.ID)
	res, err := httpclient.EnsureSuccessful().Get(r, url)
	if err == nil {
		recommendations, err = res.JSON[[]map[string]any]()
	}
	if err != nil {
		r.Report(err)
	}

	return web.View("products.show", map[string]any{
		"Product":         product,
		"Recommendations": recommendations,
	})
}

r.Report logs the error with the request's context and passes it to your report hook. It skips expected outcomes, so reporting a 404 does nothing.

Code below the handler, such as a job or a function that a handler and a command both call, has a ctx rather than a request. That code reports with laravel.Report, which works in a request, a job, a command, a listener, or a scheduled task:

go
if err := search.Index(ctx, post); err != nil {
	laravel.Report(ctx, fmt.Errorf("indexing post %d for search: %w", post.ID, err))
}

Panics ​

If a handler or a middleware panics, Laravel recovers the panic, reports a *web.PanicError that holds the panic's value and its stack, and renders a 500 response while your application continues serving other requests. Even so, return errors for failures you anticipate and reserve panics for bugs.

警告

Laravel doesn't recover a panic in a goroutine that you start yourself, so that panic ends the whole process. Start the work with r.Background, which recovers and reports a panic, or recover in the goroutine yourself.

Error pages ​

Requests that expect JSON, along with every request to a route in routes/api.go, receive errors as JSON, such as {"message": "Not Found"}. All other requests receive an HTML error page.

In JSON, the message comes from the error that set the status code, whether passed to web.Abortf or web.Errorf, or returned by the Error method of an error with a StatusCode method:

go
return web.Abortf(http.StatusNotFound, "That post doesn't exist.")

For example, failing with a *billing.DeclinedError (402) produces "The card was declined: insufficient funds", even if you wrapped context around it. web.Abort produces the status's reason phrase, such as "Not Found" or "Page Expired", and a missing database row produces "Not Found" outside debug mode. Server failures produce "Server Error" unless debug mode is on or you used web.Abort or web.Abortf.

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 a web.ErrorPage with the Status, its Title, such as "Not Found", and the Message the page shows:

html
{{template "layout" .}}

{{define "content"}}
	<h1>{{.Status}}</h1>
	<p>{{.Message}}</p>
{{end}}

If your application uses Inertia, you may render errors with a frontend page component instead. Name the component in the ErrorPage field of inertia.Middleware in bootstrap/app.go, as new applications do with ErrorPage: "Error". To learn more, check out the Inertia guide's section on error pages.

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, set the Errors option in bootstrap/app.go. Each field of web.Errors is optional, so you may set only the ones you need:

go
package bootstrap

import (
	laravel "go.laravel.com"
	"go.laravel.com/web"
)

func Options() laravel.Options {
	return laravel.Options{
		Errors: web.Errors{
			Ignore:  ignoreError,
			Report:  reportError,
			Render:  renderError,
			Respond: finishError,
		},

		// ...
	}
}

The sections below define each of these functions in the bootstrap package.

Reporting errors ​

Laravel logs every server failure automatically, at the error level. To also send failures to an external service, set the Report function. Laravel calls it with each reported error and the context it was reported in. During a request, the context is the *web.Request itself, so you may read the request's route. An error that laravel.Report reports from a job or a command has no request, and neither does the error that a command, a queued job, or a scheduled task fails with, which Laravel reports too:

go
func reportError(ctx context.Context, err error) {
	if r, ok := ctx.(*web.Request); ok {
		// Tag the error with r.Route().Name...
	}

	// Send the error to your error tracker...
}

If your error tracker integrates with slog, such as Sentry, you don't need a Report function. Laravel logs every failure at the error level, so adding the tracker's slog handler captures them automatically.

A Go error carries no stack trace. To help you find where a failure happened, Laravel adds a location field to the log line, holding the file and line where a handler or middleware called web.Fail, web.Abort, or web.Abortf. Every reported error also records its Go type:

text
level=ERROR msg="charge failed: connection refused" method=POST path=/orders location=/srv/app/handlers/orders/orders.go:42 type=*net.OpError request_id=6f1c0a9d2b3e4f5a8c7d9e0f1a2b3c4d

Ignoring errors ​

To keep expected failures out of your logs and your error tracker, return true from Ignore for each error that Laravel shouldn't report. For example, an application that already monitors its search service elsewhere might ignore that service's errors:

go
func ignoreError(err error) bool {
	return errors.Is(err, search.ErrUnavailable)
}

Ignored errors still render responses as usual.

Rendering errors ​

To render some errors your own way, set the Render function. It receives the request and the error, and returns the response to send, or nil to fall back to Laravel's default rendering. Laravel calls Render for every error, including a 404 for a path that no route matches, and before an error's own Respond method.

For example, if your blog moved to its own domain, this function redirects the old /blog/ addresses to the new domain and leaves every other error to Laravel:

go
func renderError(r *web.Request, err error) *web.Response {
	if web.StatusOf(err) == http.StatusNotFound && strings.HasPrefix(r.URL.Path, "/blog/") {
		return web.Redirect("https://blog.example.com" + strings.TrimPrefix(r.URL.Path, "/blog"))
	}

	return nil
}

Laravel sends whatever response Render returns, so set its status with WithStatus when it shows an error, or the response will be 200 OK. When Render builds a page of its own, show the error with web.PublicMessage(r, err) rather than err.Error(), so the page leaves out your context and says "Server Error" for a failure outside debug mode.

Adjusting every error response ​

To modify every rendered error response, set the Respond function. It receives the request, the rendered response, and the error, and returns the response to send, whether Render built the response or Laravel did. For example, this function prevents browsers and proxies from caching error pages:

go
func finishError(r *web.Request, res *web.Response, err error) *web.Response {
	return res.WithHeader("Cache-Control", "no-store")
}

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 in the DontFlash field, using "dot" notation for nested fields:

go
Errors: web.Errors{
	DontFlash: []string{"ssn", "card.number", "card.cvc"},
},

Laravel also leaves out these fields when you flash input yourself with WithInput on a redirect.

Errors from packages ​

Packages configure their own errors by passing a web.Errors to app.Errors in their package's Register method. Your application's Errors option applies after every package's, so your Render runs before a package's, and your Respond sees the response last. To learn more about registering errors in a package, check out the package development guide's section on errors.

Inspecting errors ​

Inside your error handler's functions and your tests, you may inspect an error with these functions:

FunctionReturns
web.StatusOf(err)The status the error responds with, such as 402, or 500 for an error that chooses none.
web.PublicMessage(r, err)The message the error's response shows the user.
errors.Is(err, billing.ErrBelowMinimum)Whether the error is or wraps billing.ErrBelowMinimum.
errors.AsType[*billing.DeclinedError](err)The underlying *billing.DeclinedError, if there is one.
err.Error()Its whole message, including any context you wrapped around it.

Testing errors ​

In HTTP tests, each response retains the error it was rendered from, so you may assert directly on errors rather than matching HTML text. Use AssertError to check the rendered error with errors.Is, AssertReportedWhere to check that the request reported an error of a given type (including one passed to r.Report), and AssertNothingReported to verify that no failures were reported at all:

go
package feature_test

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"testing"

	"go.laravel.com/httpclient"
	"go.laravel.com/httpclienttest"
	"go.laravel.com/model"

	"app/billing"
	"app/models"
	"app/tests"
)

func TestASmallChargeIsRejected(t *testing.T) {
	client := tests.New(t)

	client.Post("/checkout", url.Values{"amount": {"10"}}).
		AssertStatus(http.StatusUnprocessableEntity).
		AssertError(billing.ErrBelowMinimum).
		AssertNothingReported()
}

func TestProductsShowWithoutRecommendations(t *testing.T) {
	client := tests.New(t)
	httpclienttest.New(client).
		Respond("recommendations.example.com/*", httpclienttest.FailedConnection())

	product := models.Product{Name: "Desk lamp"}
	if err := model.Create(client.Context(), &product); err != nil {
		t.Fatal(err)
	}

	client.Get(fmt.Sprintf("/products/%d", product.ID)).
		AssertOK().
		AssertReportedWhere(func(err *httpclient.ConnectionError) bool {
			return strings.HasPrefix(err.URL, "https://recommendations.example.com/")
		})
}

AssertReportedWhere finds a reported error of the type its function takes, as errors.AsType does, and passes when the function returns true. To check the type and fields of the error the response was rendered from, use AssertErrorWhere. To check a reported error with errors.Is, use AssertReported, or AssertNotReported for an error that shouldn't be reported:

go
client.Post("/checkout", url.Values{"card": {"4000000000000002"}}).
	AssertErrorWhere(func(err *billing.DeclinedError) bool {
		return err.Reason == "insufficient funds"
	}).
	AssertNotReported(billing.ErrBelowMinimum)

When laravel.Report reports an error outside a request, such as from a job that the test runs with client.Attempt, no response holds that error. Call AssertReported on the test client instead, which records every error the application reported during the test:

go
client.Attempt(jobs.PublishPost{PostID: post.ID}).AssertSucceeded()
client.AssertReported(search.ErrUnavailable)

The application under test runs in debug mode and logs to the test, so when a request fails with a 500 you didn't expect, the test's output shows the error that caused it.