1

guys. I am new to Laravel. Just installed 5.5 and try to catch the AuthenticationException in App\Exceptions\Handler like below

public function render($request, Exception $exception)
{
    if ($exception instanceof AuthenticationException) {
        //Do something
    }
}

The problem is ($exception instanceof AuthenticationException) always return false.

dd($exception instanceof AuthenticationException) //return false.

When I dd($exception) I got

AuthenticationException{
    #gurad...
    ....
    .....
}

Then I try

get_class($exception) return \Illuminate\Auth\AuthenticationException

However,

dd($exception instanceof Exception) //return true.

Please help. Thanks.

zyc
  • 41
  • 1
  • 5

1 Answers1

4

You should make sure you use class from valid namespace:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
        //Do something
    }

    return parent::render($request, $exception);
}

You mentioned:

dd($exception instanceof Exception) //return true.

That's true. Each exception class that will extend Exception class will return true for this, that's why in your handler you should make sure you first verify specific classes and not exception class, for example if you used:

public function render($request, Exception $exception)
{
    if ($exception instanceof Exception) {
        //Do something 1
    }
    if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
        //Do something 2
    }

    return parent::render($request, $exception);
}

always //Do something 1 would be launched first.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • I tried `if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException\MethodNotAllowedException)` but still returns false. However on the browser it says the error is with the method not allowed. – Jim Apr 16 '19 at 07:59