Laravel 5.5 $exception instanceof AuthenticationException 没有按预期工作

Laravel 5.5 $exception instanceof AuthenticationException not working as expected

伙计们。我是 Laravel 的新手。刚刚安装了 5.5 并尝试在 App\Exceptions\Handler 中捕获 AuthenticationException,如下所示

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

问题是($exception instanceof AuthenticationException)总是return false。

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

当我 dd($exception) 我得到了

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

那我试试

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

然而,

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

请帮忙。谢谢。

您应该确保使用来自有效命名空间的 class:

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

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

您提到:

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

没错。每个将扩展异常 class 的异常 class 都将 return 为真,这就是为什么在您的处理程序中您应该确保首先验证特定的 classes 而不是异常 class,例如,如果您使用:

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);
}

总是//Do something 1会先启动。