我正在使用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中的其他异常?
答案 0 :(得分:4)
我似乎忘了使用命名空间:
if($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException)
{
return jsend()->error()
->message("Token Expired")
->code(403)
->data([null])
->get();
}
小错误! 捂脸
答案 1 :(得分:3)
如果有人想知道新的Laravel(5.4)和jwt-auth(1.0。* @ dev)存在同样的问题......现在还有另一个原因/解决方案。
Provider捕获\Tymon\JWTAuth\Exceptions\TokenExpiredException
的实例并重新生成Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
的实例。方法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);
}