处理 Laravel 中的 jwt auth 错误

Sin*_*ina 2 api error-handling token jwt laravel


我正在做一个休息 api 项目。
我在一个问题上挣扎。当我收到令牌过期错误时,生成的代码将是这样的:

public function authenticate(Request $request){
    $this->checkForToken($request);

    try {
        if (! $this->auth->parseToken()->authenticate()) {
            throw new UnauthorizedHttpException('jwt-auth', 'User not found');
        }
    } catch (JWTException $e) {
        throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码写在这个文件中:

供应商/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php


如何将其作为 JSON 类型返回?

Con*_*hol 5

App\Exceptions\Handler类的渲染方法中捕获该异常并返回格式为 json 的响应:

// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...

public function render($request, Exception $exception)
{   

  // if your api client has the correct content-type this expectsJson() 
  // should work. if not you may use $request->is('/api/*') to match the url.


  if($request->expectsJson()) 
  {

    if($exception instanceof UnauthorizedHttpException) {

      return response()->json('Unauthorized', 403);

    }

  }

  return parent::render($request, $e);

}
Run Code Online (Sandbox Code Playgroud)