Laravel无法捕获异常:如何捕获包内中间件抛出的异常?
Let me walk you through how to properly catch that JWT middleware exception in your Laravel exception handler. I've run into this exact issue before, so here's what you need to do:
1. Verify the Exception Namespace
First, make sure you're targeting the correct exception class. The UnauthorizedHttpException you're throwing lives in the Symfony namespace, not a custom one. Add these imports to your app/Exceptions/Handler.php file:
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; // If you want to specifically target JWT-related root exceptions, also add: use Tymon\JWTAuth\Exceptions\JWTException;
2. Update the render Method to Prioritize This Exception
The key here is to add your custom handling before calling the parent render method. Laravel processes exceptions in the order you check them, so specific exceptions need to come first.
Here's how to modify your render method:
public function render($request, Throwable $e) { // Option 1: Catch ONLY JWT-related UnauthorizedHttpExceptions if ($e instanceof UnauthorizedHttpException && $e->getPrevious() instanceof JWTException) { return response()->json([ 'status' => 'error', 'code' => 401, 'message' => $e->getMessage() ], 401); } // Option 2: Catch ALL UnauthorizedHttpExceptions (for a unified 401 response) // if ($e instanceof UnauthorizedHttpException) { // return response()->json([ // 'status' => 'error', // 'code' => $e->getStatusCode(), // 'message' => $e->getMessage() // ], $e->getStatusCode()); // } // Let Laravel handle other exceptions normally return parent::render($request, $e); }
3. Check for Common Pitfalls
- Middleware Execution Order: Ensure your JWT middleware is registered correctly in
app/Http/Kernel.php(usually in theapimiddleware group) and that no other middleware is swallowing the exception before it reaches the handler. - API vs Web Requests: If you're building an API, wrap the response logic with
$request->wantsJson()to ensure you only return JSON for API requests:if ($e instanceof UnauthorizedHttpException && $request->wantsJson()) { // Return your custom JSON response here } - JWT Package Configuration: Double-check that your
tymon/jwt-authpackage isn't overriding exception handling. The default config doesn't do this, but if you've modifiedconfig/jwt.php, ensure there's no custom exception handler set there.
That should do it! This setup will catch the UnauthorizedHttpException thrown from your JWT middleware and let you return a custom response instead of Laravel's default one.
内容的提问来源于stack exchange,提问作者Stefano Maglione

