Laravel Tutorials

Always Render API Exceptions as JSON in Laravel

Published
Always Render API Exceptions as JSON in Laravel image

Have you ever enforced returning JSON on API requests for exceptions using a custom middleware like the following:

class ForceJsonResponse
{
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
 
return $next($request);
}
}

Laravel 11 gives you a handy way to do this without any extra middleware. I think it's really nice if you are using a web browser to test API routes and always get JSON even without setting the Accept header to application/json or using the above middleware:

// bootstrap/app.php
 
return Application::configure(basePath: dirname(__DIR__))
 
//...
 
->withExceptions(function (Exceptions $exceptions) {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
}
 
return $request->expectsJson();
});
})->create();

Using the shouldRenderJsonWhen() method, this code ensures that any exceptions thrown during an API request are rendered as JSON. Besides exceptions, it's up to you to ensure non-error responses return JSON.

This tip comes straight from the documentation, which also has some excellent tips on throttling exceptions, customizing error responses, and more!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article