伙计们。我是 Laravel 的新手。刚刚安装了 5.5 并尝试在 App\Exceptions\Handler 中捕获 AuthenticationException,如下所示
public function render($request, Exception $exception)
{
if ($exception instanceof AuthenticationException) {
//Do something
}
}
问题是 ($exception instanceof AuthenticationException) 总是返回 false。
dd($exception instanceof AuthenticationException) //return false.
当我 dd($exception) 时,我得到了
AuthenticationException{
#gurad...
....
.....
}
那我试试
get_class($exception) return \Illuminate\Auth\AuthenticationException
但是,
dd($exception instanceof Exception) //return true.
请帮忙。谢谢。
最佳答案
您应该确保使用有效 namespace 中的类:
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.
确实如此。每个扩展 Exception 类的异常类都会为此返回 true,这就是为什么在处理程序中您应该确保首先验证特定类而不是异常类,例如,如果您使用:
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
将首先启动。
关于php - Laravel 5.5 $exception instanceof AuthenticationException 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46589843/