laravel-5.4 - Laravel 错误处理,get_class 与 instanceof

标签 laravel-5.4 laravel-exceptions

在 app/Exceptions/Handler.php 中的以下代码中,第一个不起作用,但第二个起作用。
dd(get_class($exception));输出“Illuminate\Database\Eloquent\ModelNotFoundException”。

第一个是 similar to the doc .如何使用 instanceof 使其工作?

    public function render($request, Exception $exception)
    {
        //dd(get_class($exception));
        // this does not work.
        if ($exception instanceof Illuminate\Database\Eloquent\ModelNotFoundException
) {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }
        // This one works.
        if(get_class($exception) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }

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

最佳答案

使用 instanceof你必须使用完整的类名,如果你的类有一个命名空间,那么你应该使用类的全限定类名。

还有另一种使用方式 instanceof感谢 use 为给定的类使用短名称(别名)声明,在您的情况下,您可以像这样使用它:

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; // on top of course :) 

if ($exception instanceof ModelNotFoundException) {
        return response()->json(['error'=>['message'=>'Resouce not found']], 404);
}

关于laravel-5.4 - Laravel 错误处理,get_class 与 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44927794/

相关文章:

php - 分组的 Laravel 路由会被缓存吗?它们缓存在哪里?

php - 如何在 Laravel 中正确更新密码?

sql-server - SQLSTATE[IMSSP] : Tried to bind parameter number 2101. SQL Server 支持最多 2100 个参数

composer-php - 编译服务类已被删除 Composer 错误 laravel 5.4

php - Laravel 异常 405 方法不允许

php - Laravel 自定义异常

Laravel 5.7 如何使用 URL 记录 404

php - 如何获取从 PUT 方法传递的数据