You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel无法捕获异常:如何捕获包内中间件抛出的异常?

Solution: Catching JWT Middleware's UnauthorizedHttpException in Laravel's Exception Handler

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 the api middleware 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-auth package isn't overriding exception handling. The default config doesn't do this, but if you've modified config/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:51:56