Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 484
Rohan Avatar asked Oct 30 '15 06:10

Rohan


2 Answers

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

like image 176
Rohan Avatar answered Oct 02 '22 06:10

Rohan


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);
}
like image 20
Rok Jarc Avatar answered Oct 02 '22 07:10

Rok Jarc