7

我正在使用 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);
}

如何处理 Laravel 中的其他异常?

4

2 回答 2

4

看来我忘了使用命名空间:

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

小错误!掌心

于 2015-11-03T09:36:29.787 回答
3

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

提供者捕获 的实例\Tymon\JWTAuth\Exceptions\TokenExpiredException并重新抛出 的实例Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException。原始异常仍然可用于 method getPrevious(),因此错误处理现在看起来像这样:

public function render($request, Exception $exception)
{        
    if ($exception->getPrevious() instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
        return response()->json(['error' => $exception->getPrevious()->getMessage()], $exception->getStatusCode());
    } else if ($exception->getPrevious() instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
        return response()->json(['error' => $exception->getPrevious()->getMessage()], $exception->getStatusCode());
    }

    return parent::render($request, $exception);
}
于 2017-03-07T13:17:25.983 回答