php - Laravel 5.5 $exception instanceof AuthenticationException 未按预期工作

标签 php laravel authentication exception instanceof

伙计们。我是 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/

相关文章:

asp.net-mvc-3 - 在多个 ASP MVC 3 应用程序中单点登录

php - 网 bean 7.3.1 : is there a way to automatically insert ; at the end of the line for PHP files?

php - 是否可以使用 Eloquent 方式为模型获取不同模型类型的集合?

php - 如何在 Laravel 5.2 中手动发送密码重置请求?

php - laravel save() 方法是否抛出异常?

从 native 应用程序进行 Azure Active Directory 身份验证,无需用户登录

php - Symfony2 : Read Cookie

php - 在 Laravel 5.1 中缓存延迟加载查询

php - 谷歌地图标记太大

authentication - 为什么不允许密码认证?