Laravel Middleware Order Will Silently Swallow Your Exception Handler
A production bug that took me hours to track down: global middleware running before the exception handler can eat your errors whole, with no warning anywhere.
Global middleware order in Laravel can silently swallow your exception handler, and the framework will not say a word about it. No log entry, no stack trace, no 500 response with any useful context. Just a blank response or an empty JSON body, depending on how your middleware terminates the request. I hit this on a production API for a healthcare client and spent the better part of a day staring at CloudWatch before I understood what was actually happening.
The Setup That Looks Fine
Laravel processes HTTP middleware in a stack. The framework itself wraps the whole request/response cycle in a couple of core middleware classes before it ever touches your app/Http/Middleware stack. The one you care about is Illuminate\Foundation\Http\Middleware\HandleExceptions - that's what converts PHP errors and uncaught exceptions into proper HTTP responses routed through your App\Exceptions\Handler.
Here's the trap: any middleware you register in the global stack that runs before HandleExceptions can throw or return a response before the exception handler is ever wired up. And in Laravel 10/11, you have more control over that ordering than you might realize - which means more rope to hang yourself with.
The client project was a Laravel 10 API. We had a custom middleware that validated a shared secret on inbound webhook payloads before anything else touched the request. Reasonable enough. It looked like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ValidateWebhookSignature
{
public function handle(Request $request, Closure $next): Response
{
$secret = config('services.webhook_secret');
// This will throw if the config key is missing or null
if (! hash_equals($secret, $request->header('X-Webhook-Secret', ''))) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
Nothing obviously wrong. But we registered it at the top of $middleware in Kernel.php, before the framework's own exception-handling middleware had fully initialized in the request lifecycle. When config('services.webhook_secret') returned null in a specific environment (a misconfigured .env on a new container) and hash_equals got a null first argument, PHP threw a ValueError. That error had nowhere to go. HandleExceptions hadn't wrapped this layer yet. The exception vanished. The response was empty. The client's monitoring just saw connection resets.
Where the Ordering Actually Lives
In Laravel 10 with the classic Kernel.php, your global middleware array is processed in this order:
// In App\Http\Kernel, $middleware array
protected $middleware = [
// Laravel prepends its own core middleware before this list,
// but the ORDERING within this list is on you.
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
The framework's HandleExceptions is prepended automatically by the Application class before this list. So in theory, your custom middleware should always be downstream of it. In theory.
The problem comes from two places:
-
Laravel 11's new bootstrap and
withMiddlewareAPI - the new application structure gives you even more direct control over prepending and appending to the middleware stack, and it's very easy to prepend something before the core group without realizing it. -
Custom
Applicationsubclasses or service providers that modify the middleware pipeline early. We had one of these. A previous developer had extendedIlluminate\Foundation\Applicationto do some multi-tenancy bootstrapping, and in doing so, theregisterCoreContainerAliasestiming was slightly off. Good intentions, subtle disaster.
In Laravel 11, the equivalent is in bootstrap/app.php:
<?php
use Illuminate\Foundation\Application;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
)
->withMiddleware(function (Middleware $middleware) {
// If you use prepend() here carelessly, you can get ahead of
// the exception handling pipeline
$middleware->prepend(\App\Http\Middleware\ValidateWebhookSignature::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Calling $middleware->prepend() pushes your class to the front of the stack. If your middleware can throw before HandleExceptions has a chance to catch, you are in trouble.
How to Actually Debug This
The first thing I do now when a Laravel app produces blank or malformed responses in production but nothing appears in logs is check dd() early in the pipeline. Not in a controller - in the middleware itself, before the $next($request) call. If dd() doesn't fire, the request isn't reaching that layer.
The second thing is to temporarily wrap the middleware body in a broad try/catch and log manually:
public function handle(Request $request, Closure $next): Response
{
try {
$secret = config('services.webhook_secret');
if (! hash_equals((string) $secret, $request->header('X-Webhook-Secret', ''))) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
} catch (\Throwable $e) {
// If you're seeing this log entry, exception handling is broken
// above this layer. Fix the middleware order, don't keep this catch.
\Log::critical('Middleware exception bypassed handler', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return response()->json(['error' => 'Internal Server Error'], 500);
}
}
I want to be clear: that catch block is a diagnostic tool, not a solution. If you're seeing that log entry, the fix is to correct the middleware ordering, not to absorb exceptions in every middleware class you write.
The permanent fix is simpler. Cast aggressively, validate early, and don't let middleware throw when you can return cleanly instead:
public function handle(Request $request, Closure $next): Response
{
$secret = (string) config('services.webhook_secret', '');
$provided = (string) $request->header('X-Webhook-Secret', '');
// If the secret is not configured, fail closed rather than throwing
if (empty($secret) || ! hash_equals($secret, $provided)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
And audit your Kernel.php or bootstrap/app.php for anything using prepend() that could fire before core Laravel bootstrapping is done.
The Gotchas I'd Add to the Docs If I Could
CORS middleware can do this too. HandleCors runs very early. If you have custom CORS middleware and it throws on a malformed Origin header, the same thing happens. I've seen this bite teams using fruitcake/laravel-cors on older projects during upgrades.
Telescope and Debugbar are not immune. Both packages hook into the request lifecycle early. If you have one of these installed and your exception handler is broken, you will not see the exception in those tools either. That's the tell: if Telescope isn't recording an exception that you know occurred, the exception happened above the instrumentation layer.
Queue workers are a separate problem. This whole post is about the HTTP kernel. The console kernel has its own middleware stack and its own exception handling. Don't assume fixing the HTTP pipeline fixes your jobs.
Laravel Octane makes this worse. Because Octane keeps the application bootstrapped between requests, a corrupted middleware pipeline state from one request can bleed into the next. The blank response might be intermittent and even harder to reproduce.
When to Be Paranoid About This
Any time I'm registering a middleware that needs to run very early - signature validation, tenant resolution, IP allowlisting - I think about whether that middleware can throw. If it can, I either make it return a response instead of throwing, or I make sure it's not prepended ahead of the core Laravel exception pipeline.
I'd be especially careful in these situations:
- Custom
Applicationsubclasses for multi-tenancy or custom bootstrapping - Any package that calls
$app->make('kernel')early in a service provider - Laravel 11 apps using
$middleware->prepend()inbootstrap/app.php - Anything involving early config access where the config might not be loaded yet
I wouldn't worry about this for standard route middleware or middleware group entries. Those always run after the exception handler is wired up. This is specifically a global middleware ordering concern.
The Takeaway
The framework's exception handling isn't magic that wraps everything - it's just another middleware class, and if you put something in front of it that can throw, you've blinded your own error reporting. Took me a full day and a production incident to really internalize that.
Keep your early-pipeline middleware boring and defensive. Return responses, don't throw exceptions, and cast your inputs before you touch them. The exception handler is a safety net, not a guarantee.
Need help shipping something like this? Get in touch.