How to catch global exceptions in laravel 5 generated by the tymondesigns/jwt-auth package?
Asked Answered
L

2

7

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?

Lussier answered 30/10, 2015 at 6:43 Comment(0)
L
4

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

Lussier answered 3/11, 2015 at 9:36 Comment(1)
Does this still work with Laravel 5.4? Because I have set it up as above but it still does not catching the exceptionSouth
S
3

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);
}
Smarm answered 7/3, 2017 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.