如何在 tymondesigns/jwt-auth 包生成的 laravel 5 中捕获全局异常



>我正在使用Laravel 5开发RESTful应用程序,我正在尝试捕获异常并生成适当的响应。我还使用 tymondesigns/jwt-auth 包,以便所有 API 响应都是 JSend JSON 格式。

现在我正在尝试捕捉给定令牌过期时出现的TokenExpiredException。所以我在Handler.php中尝试了这个:

if($e instanceof TokenExpiredException)
{
    return jsend()->error()
          ->message("Token Expired")
          ->code(403)
          ->data([null])
          ->get();
}

但我仍然无法捕获此异常并返回 JSON 响应。尽管我可以为其他例外情况执行此操作,例如:

if ($e instanceof ModelNotFoundException) {
    $e = new NotFoundHttpException($e->getMessage(), $e);
    return jsend()->error()
              ->message("404 Model Not Found")
              ->data([null])
              ->get();
}

和:

if ($this->isHttpException($e))
{       
    if($e instanceof NotFoundHttpException)
    {
        return jsend()->error()
              ->message("404 Route Not Found")
              ->data([null])
              ->get();
    }
    return $this->renderHttpException($e);
}

如何处理拉拉维尔中的其他异常?

似乎我忘了使用命名空间:

if($e instanceof TymonJWTAuthExceptionsTokenExpiredException)
{
    return jsend()->error()
          ->message("Token Expired")
          ->code(403)
          ->data([null])
          ->get();
}

小错误!脸掌

如果有人在这里想知道新的 Laravel(5.4( 和 jwt-auth (1.0.*@dev(同样的问题......现在还有另一个原因/解决方案。

提供程序捕获 TymonJWTAuthExceptionsTokenExpiredException 的实例并重新抛出SymfonyComponentHttpKernelExceptionUnauthorizedHttpException的实例。方法 getPrevious() 仍然提供原始异常,因此错误处理现在如下所示:

public function render($request, Exception $exception)
{        
    if ($exception->getPrevious() instanceof TymonJWTAuthExceptionsTokenExpiredException) {
        return response()->json(['error' => $exception->getPrevious()->getMessage()], $exception->getStatusCode());
    } else if ($exception->getPrevious() instanceof TymonJWTAuthExceptionsTokenInvalidException) {
        return response()->json(['error' => $exception->getPrevious()->getMessage()], $exception->getStatusCode());
    }
    return parent::render($request, $exception);
}

最新更新