I am working on a RESTful application using Laravel 5 and I am trying to catch exceptions and generate an appropriate response. I am also using the tymondesigns/jwt-auth package so that all the API responses are in JSend JSON format.
Right now I am trying to catch the TokenExpiredException which arises when the given token is expired of course. So I tried this in the Handler.php:
if($e instanceof TokenExpiredException)
{
    return jsend()->error()
          ->message("Token Expired")
          ->code(403)
          ->data([null])
          ->get();
}
But I am still not able to catch this exception and give back a JSON response. Although I am able to do this for other exceptions like:
if ($e instanceof ModelNotFoundException) {
    $e = new NotFoundHttpException($e->getMessage(), $e);
    return jsend()->error()
              ->message("404 Model Not Found")
              ->data([null])
              ->get();
}
And:
if ($this->isHttpException($e))
{       
    if($e instanceof NotFoundHttpException)
    {
        return jsend()->error()
              ->message("404 Route Not Found")
              ->data([null])
              ->get();
    }
    return $this->renderHttpException($e);
}
How to handle other exceptions in Laravel?
It seems I forgot to use the namespace:
if($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException)
{
    return jsend()->error()
          ->message("Token Expired")
          ->code(403)
          ->data([null])
          ->get();
}
Small mistakes! facepalm
If someone comes wondering here with same problem for new Laravel (5.4) and jwt-auth (1.0.*@dev)... now there is another cause/solution to this.
Provider catches instance of \Tymon\JWTAuth\Exceptions\TokenExpiredException and rethrows instance of Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException. Original exception is still available with method getPrevious(), so error handling would now look something like this:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With