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 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:
1APP_DEBUG=true1APP_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:
1package users23import (4 "go.laravel.com/model"5 "go.laravel.com/web"67 "app/models"8)910func Show(r *web.Request) *web.Response {11 user, err := model.FromRoute[models.User](r, "user")12 if err != nil {13 return web.Fail(err)14 }1516 return web.JSON(user)17}1package users23import (4 "go.laravel.com/model"5 "go.laravel.com/web"67 "app/models"8)910func Show(r *web.Request) *web.Response {11 user, err := model.FromRoute[models.User](r, "user")12 if err != nil {13 return web.Fail(err)14 }1516 return web.JSON(user)17}
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:
1func headerRow(contents string) (string, error) {2 header, _, _ := strings.Cut(contents, "\n")3 if header == "" {4 return "", errors.New("the import file has no header row")5 }67 return header, nil8}1func headerRow(contents string) (string, error) {2 header, _, _ := strings.Cut(contents, "\n")3 if header == "" {4 return "", errors.New("the import file has no header row")5 }67 return header, nil8}
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:
1package billing23import "errors"45// ErrBelowMinimum means the amount is too small to charge.6var ErrBelowMinimum = errors.New("The amount is below the minimum.")78// A DeclinedError means the card issuer declined the charge.9type DeclinedError struct {10 Reason string11}1213func (e *DeclinedError) Error() string {14 return "The card was declined: " + e.Reason15}1package billing23import "errors"45// ErrBelowMinimum means the amount is too small to charge.6var ErrBelowMinimum = errors.New("The amount is below the minimum.")78// A DeclinedError means the card issuer declined the charge.9type DeclinedError struct {10 Reason string11}1213func (e *DeclinedError) Error() string {14 return "The card was declined: " + e.Reason15}
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:
1if declined, ok := errors.AsType[*billing.DeclinedError](err); ok {2 // Show declined.Reason to the customer...3}1if declined, ok := errors.AsType[*billing.DeclinedError](err); ok {2 // Show declined.Reason to the customer...3}
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:
1func (e *DeclinedError) StatusCode() int {2 return http.StatusPaymentRequired3}1func (e *DeclinedError) StatusCode() int {2 return http.StatusPaymentRequired3}
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:
1// ErrBelowMinimum means the amount is too small to charge.2var ErrBelowMinimum = belowMinimum{}34type belowMinimum struct{}56func (belowMinimum) Error() string { return "The amount is below the minimum." }7func (belowMinimum) StatusCode() int { return http.StatusUnprocessableEntity }1// ErrBelowMinimum means the amount is too small to charge.2var ErrBelowMinimum = belowMinimum{}34type belowMinimum struct{}56func (belowMinimum) Error() string { return "The amount is below the minimum." }7func (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:
1results, err := search.Posts(r, filters.Query)2if err != nil {3 return web.Fail(&web.Error{Status: http.StatusServiceUnavailable, Err: err})4}1results, err := search.Posts(r, filters.Query)2if err != nil {3 return web.Fail(&web.Error{Status: http.StatusServiceUnavailable, Err: err})4}
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:
1package billing23import (4 "net/http"56 "go.laravel.com/web"7)89// ErrSubscriptionRequired sends the user to the plans page.10var ErrSubscriptionRequired = subscriptionRequired{}1112type subscriptionRequired struct{}1314func (subscriptionRequired) Error() string { return "A subscription is required." }1516func (subscriptionRequired) Respond(r *web.Request) *web.Response {17 if r.ExpectsJSON() {18 return web.Abort(http.StatusPaymentRequired)19 }2021 return web.RedirectRoute("billing.plans")22}1package billing23import (4 "net/http"56 "go.laravel.com/web"7)89// ErrSubscriptionRequired sends the user to the plans page.10var ErrSubscriptionRequired = subscriptionRequired{}1112type subscriptionRequired struct{}1314func (subscriptionRequired) Error() string { return "A subscription is required." }1516func (subscriptionRequired) Respond(r *web.Request) *web.Response {17 if r.ExpectsJSON() {18 return web.Abort(http.StatusPaymentRequired)19 }2021 return web.RedirectRoute("billing.plans")22}
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:
1post, err := model.FromRoute[models.Post](r, "post")2if err != nil {3 return web.Fail(fmt.Errorf("loading post %s for editing: %w", r.PathValue("post"), err))4}1post, err := model.FromRoute[models.Post](r, "post")2if err != nil {3 return web.Fail(fmt.Errorf("loading post %s for editing: %w", r.PathValue("post"), err))4}
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:
1package posts23import (4 "net/http"56 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10)1112func Destroy(r *web.Request) *web.Response {13 post, err := model.FromRoute[models.Post](r, "post")14 if err != nil {15 return web.Fail(err)16 }1718 if post.UserID != models.CurrentUser(r).ID {19 return web.Abort(http.StatusForbidden)20 }2122 // Delete the post...2324 return web.RedirectRoute("posts.index")25}1package posts23import (4 "net/http"56 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10)1112func Destroy(r *web.Request) *web.Response {13 post, err := model.FromRoute[models.Post](r, "post")14 if err != nil {15 return web.Fail(err)16 }1718 if post.UserID != models.CurrentUser(r).ID {19 return web.Abort(http.StatusForbidden)20 }2122 // Delete the post...2324 return web.RedirectRoute("posts.index")25}
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:
1return web.Abortf(http.StatusConflict, "The name %q is taken.", user.Name)1return 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:
1func Resolve(ctx context.Context, ticket *models.Ticket) error {2 if ticket.Status == models.StatusResolved {3 return web.Errorf(http.StatusConflict, "Ticket #%d is already resolved.", ticket.ID)4 }56 // Resolve the ticket...78 return nil9}1func Resolve(ctx context.Context, ticket *models.Ticket) error {2 if ticket.Status == models.StatusResolved {3 return web.Errorf(http.StatusConflict, "Ticket #%d is already resolved.", ticket.ID)4 }56 // Resolve the ticket...78 return nil9}
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:
1return web.Abort(http.StatusServiceUnavailable).WithHeader("Retry-After", "60")1return 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:
1return &web.Error{2 Status: http.StatusTooManyRequests,3 Message: "You've already exported your data this minute. Try again shortly.",4 Header: http.Header{"Retry-After": {"60"}},5}1return &web.Error{2 Status: http.StatusTooManyRequests,3 Message: "You've already exported your data this minute. Try again shortly.",4 Header: http.Header{"Retry-After": {"60"}},5}
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:
1return web.Invalid("email", "That email is already invited.")1return 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:
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 report hook, and hides their message from users outside debug mode. - Expected outcomes have any other status, usually a
4xxclient status such as404,403, or422. 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:
1package products23import (4 "fmt"56 "go.laravel.com/httpclient"7 "go.laravel.com/model"8 "go.laravel.com/web"910 "app/models"11)1213func Show(r *web.Request) *web.Response {14 product, err := model.FromRoute[models.Product](r, "product")15 if err != nil {16 return web.Fail(err)17 }1819 var recommendations []map[string]any2021 url := fmt.Sprintf("https://recommendations.example.com/products/%d", product.ID)22 res, err := httpclient.EnsureSuccessful().Get(r, url)23 if err == nil {24 recommendations, err = res.JSON[[]map[string]any]()25 }26 if err != nil {27 r.Report(err)28 }2930 return web.View("products.show", map[string]any{31 "Product": product,32 "Recommendations": recommendations,33 })34}1package products23import (4 "fmt"56 "go.laravel.com/httpclient"7 "go.laravel.com/model"8 "go.laravel.com/web"910 "app/models"11)1213func Show(r *web.Request) *web.Response {14 product, err := model.FromRoute[models.Product](r, "product")15 if err != nil {16 return web.Fail(err)17 }1819 var recommendations []map[string]any2021 url := fmt.Sprintf("https://recommendations.example.com/products/%d", product.ID)22 res, err := httpclient.EnsureSuccessful().Get(r, url)23 if err == nil {24 recommendations, err = res.JSON[[]map[string]any]()25 }26 if err != nil {27 r.Report(err)28 }2930 return web.View("products.show", map[string]any{31 "Product": product,32 "Recommendations": recommendations,33 })34}
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:
1if err := search.Index(ctx, post); err != nil {2 laravel.Report(ctx, fmt.Errorf("indexing post %d for search: %w", post.ID, err))3}1if err := search.Index(ctx, post); err != nil {2 laravel.Report(ctx, fmt.Errorf("indexing post %d for search: %w", post.ID, err))3}
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:
1return web.Abortf(http.StatusNotFound, "That post doesn't exist.")1return 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:
1{{template "layout" .}}23{{define "content"}}4 <h1>{{.Status}}</h1>5 <p>{{.Message}}</p>6{{end}}1{{template "layout" .}}23{{define "content"}}4 <h1>{{.Status}}</h1>5 <p>{{.Message}}</p>6{{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:
1package bootstrap23import (4 laravel "go.laravel.com"5 "go.laravel.com/web"6)78func Options() laravel.Options {9 return laravel.Options{10 Errors: web.Errors{11 Ignore: ignoreError,12 Report: reportError,13 Render: renderError,14 Respond: finishError,15 },1617 // ...18 }19}1package bootstrap23import (4 laravel "go.laravel.com"5 "go.laravel.com/web"6)78func Options() laravel.Options {9 return laravel.Options{10 Errors: web.Errors{11 Ignore: ignoreError,12 Report: reportError,13 Render: renderError,14 Respond: finishError,15 },1617 // ...18 }19}
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:
1func reportError(ctx context.Context, err error) {2 if r, ok := ctx.(*web.Request); ok {3 // Tag the error with r.Route().Name...4 }56 // Send the error to your error tracker...7}1func reportError(ctx context.Context, err error) {2 if r, ok := ctx.(*web.Request); ok {3 // Tag the error with r.Route().Name...4 }56 // Send the error to your error tracker...7}
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:
1level=ERROR msg="charge failed: connection refused" method=POST path=/orders location=/srv/app/handlers/orders/orders.go:42 type=*net.OpError request_id=6f1c0a9d2b3e4f5a8c7d9e0f1a2b3c4d1level=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:
1func ignoreError(err error) bool {2 return errors.Is(err, search.ErrUnavailable)3}1func ignoreError(err error) bool {2 return errors.Is(err, search.ErrUnavailable)3}
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:
1func renderError(r *web.Request, err error) *web.Response {2 if web.StatusOf(err) == http.StatusNotFound && strings.HasPrefix(r.URL.Path, "/blog/") {3 return web.Redirect("https://blog.example.com" + strings.TrimPrefix(r.URL.Path, "/blog"))4 }56 return nil7}1func renderError(r *web.Request, err error) *web.Response {2 if web.StatusOf(err) == http.StatusNotFound && strings.HasPrefix(r.URL.Path, "/blog/") {3 return web.Redirect("https://blog.example.com" + strings.TrimPrefix(r.URL.Path, "/blog"))4 }56 return nil7}
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:
1func finishError(r *web.Request, res *web.Response, err error) *web.Response {2 return res.WithHeader("Cache-Control", "no-store")3}1func finishError(r *web.Request, res *web.Response, err error) *web.Response {2 return res.WithHeader("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 in the DontFlash field, using "dot" notation for nested fields:
1Errors: web.Errors{2 DontFlash: []string{"ssn", "card.number", "card.cvc"},3},1Errors: web.Errors{2 DontFlash: []string{"ssn", "card.number", "card.cvc"},3},
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:
| Function | Returns |
|---|---|
web.StatusOf(err) |
The status the error responds with, such as 402, or 500 for an error that chooses none. |
web.PublicMessage(r, |
The message the error's response shows the user. |
errors.Is(err, |
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:
1package feature_test23import (4 "fmt"5 "net/http"6 "net/url"7 "strings"8 "testing"910 "go.laravel.com/httpclient"11 "go.laravel.com/httpclienttest"12 "go.laravel.com/model"1314 "app/billing"15 "app/models"16 "app/tests"17)1819func TestASmallChargeIsRejected(t *testing.T) {20 client := tests.New(t)2122 client.Post("/checkout", url.Values{"amount": {"10"}}).23 AssertStatus(http.StatusUnprocessableEntity).24 AssertError(billing.ErrBelowMinimum).25 AssertNothingReported()26}2728func TestProductsShowWithoutRecommendations(t *testing.T) {29 client := tests.New(t)30 httpclienttest.New(client).31 Respond("recommendations.example.com/*", httpclienttest.FailedConnection())3233 product := models.Product{Name: "Desk lamp"}34 if err := model.Create(client.Context(), &product); err != nil {35 t.Fatal(err)36 }3738 client.Get(fmt.Sprintf("/products/%d", product.ID)).39 AssertOK().40 AssertReportedWhere(func(err *httpclient.ConnectionError) bool {41 return strings.HasPrefix(err.URL, "https://recommendations.example.com/")42 })43}1package feature_test23import (4 "fmt"5 "net/http"6 "net/url"7 "strings"8 "testing"910 "go.laravel.com/httpclient"11 "go.laravel.com/httpclienttest"12 "go.laravel.com/model"1314 "app/billing"15 "app/models"16 "app/tests"17)1819func TestASmallChargeIsRejected(t *testing.T) {20 client := tests.New(t)2122 client.Post("/checkout", url.Values{"amount": {"10"}}).23 AssertStatus(http.StatusUnprocessableEntity).24 AssertError(billing.ErrBelowMinimum).25 AssertNothingReported()26}2728func TestProductsShowWithoutRecommendations(t *testing.T) {29 client := tests.New(t)30 httpclienttest.New(client).31 Respond("recommendations.example.com/*", httpclienttest.FailedConnection())3233 product := models.Product{Name: "Desk lamp"}34 if err := model.Create(client.Context(), &product); err != nil {35 t.Fatal(err)36 }3738 client.Get(fmt.Sprintf("/products/%d", product.ID)).39 AssertOK().40 AssertReportedWhere(func(err *httpclient.ConnectionError) bool {41 return strings.HasPrefix(err.URL, "https://recommendations.example.com/")42 })43}
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:
1client.Post("/checkout", url.Values{"card": {"4000000000000002"}}).2 AssertErrorWhere(func(err *billing.DeclinedError) bool {3 return err.Reason == "insufficient funds"4 }).5 AssertNotReported(billing.ErrBelowMinimum)1client.Post("/checkout", url.Values{"card": {"4000000000000002"}}).2 AssertErrorWhere(func(err *billing.DeclinedError) bool {3 return err.Reason == "insufficient funds"4 }).5 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:
1client.Attempt(jobs.PublishPost{PostID: post.ID}).AssertSucceeded()2client.AssertReported(search.ErrUnavailable)1client.Attempt(jobs.PublishPost{PostID: post.ID}).AssertSucceeded()2client.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.