Handling Exceptions When Request Wants JSON in Laravel 5
When implementing file uploads via AJAX, you often encounter a specific friction point between server-side validation and client-side expectations. If your upload exceeds upload_max_filesize or post_max_size, the request body becomes malformed. Consequently, the _token field is missing from the input array. This triggers the CSRF protection middleware to throw a TokenMismatchException.
The immediate problem isn't the exception itself; it's how Laravel renders the response. In debug mode, Laravel defaults to returning an HTML view with a full stack trace via the Whoops error handler. For an AJAX application expecting JSON, this breaks the frontend logic immediately. You cannot parse an HTML error page into your JavaScript object model.
The core issue here is that Laravel's global exception handling needs to be aware of the Accept header or the request's intended format before deciding whether to render a view or serialize an error object. By default, without explicit configuration, Laravel prioritizes returning HTML views for exceptions unless forced otherwise.
To resolve this in Laravel 5, you need to override the default exception renderer for specific HTTP statuses or all uncaught exceptions within your application context. The most robust approach involves creating a custom ExceptionHandler class that extends the default one and modifies how responses are generated based on the request's media type.
You can register this custom handler by overriding the $app->exceptionHandler() binding in your service provider or kernel. Here is how you can implement a custom handler:
// app/Exceptions/Handler.php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends \Illuminate\Foundation\Exceptions\Handler
{
use DispatchesJobs, ValidatesRequests, HandlesAuthorization;
/**
* Register the exception handling callbacks for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function register(Router $router)
{
parent::register($router);
// Handle all exceptions by returning JSON if requested
$this->reportable(function (Exception $exception) {
if ($this->isHttpException($exception)) {
return $this->renderHttpException($exception);
}
// Check if the request accepts JSON
if ($this->app->runningInConsole()) {
return null;
}
return $this->toJsonResponse($exception);
});
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*/
protected function render($request, Exception $e)
{
// Check if the request expects JSON based on Accept header or Content-Type
if ($request->expectsJson()) {
return $this->renderExceptionAsJson($request, $e);
}
// Otherwise, let the parent class handle HTML rendering (Whoops page)
return parent::render($request, $e);
}
/**
* Render exception as JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\JsonResponse
*/
protected function renderExceptionAsJson($request, Exception $e)
{
return response()->json([
'message' => config('app.debug') ? $e->getMessage() : 'Something went wrong.',
'error' => get_class($e),
], $e->getStatusCode());
}
/**
* Render an HTTP exception as JSON.
*
* @param \Exception $e
* @return \Illuminate\Http\JsonResponse
*/
protected function renderHttpException(HttpException $e)
{
if ($this->app->runningInConsole()) {
return null;
}
// If the user requested JSON, return JSON error
if ($this->request()->expectsJson()) {
return response()->json([
'message' => config('app.debug') ? $e->getMessage() : trans($e->getMessage()),
'error' => get_class($e),
], $e->getStatusCode());
}
// Otherwise, render the default HTML view
return parent::renderHttpException($e);
}
}
This implementation checks $request->expectsJson() to determine if the client wants a JSON payload. This method inspects both the Accept header and the Content-Type header. If the request is an AJAX call expecting JSON, the exception is serialized into a JSON response with a standard status code (e.g., 500 for internal errors or 422 for validation failures).
If the request does not expect JSON, such as a direct browser visit to a route that fails, Laravel falls back to the parent implementation, which renders the default Whoops page. This maintains the developer-friendly debugging experience in a browser environment while ensuring API clients receive structured data.
One potential pitfall is handling TokenMismatchException. Since the token is missing due to size limits, returning JSON with a generic message like "Something went wrong" might hide the fact that the upload was too large from the client. A better approach for specific validation exceptions might be to explicitly return a 422 status code with a detailed error message if config('app.debug') is true, but keep it minimal for production.
By separating the rendering logic based on the request's media type, you ensure that your AJAX endpoints remain responsive and parseable, even when server-side limits are breached. This pattern keeps your API contract consistent regardless of the underlying PHP error or validation failure.