Laravel错误处理,get_class vs instanceof [英] Laravel error handling, get_class vs instanceof

查看:260
本文介绍了Laravel错误处理,get_class vs instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在app/Exceptions/Handler.php中的以下代码中,第一个无效,但第二个无效.

In the following code in app/Exceptions/Handler.php, the first one doesn't work but the second one does.

dd(get_class($exception));输出"Illuminate \ Database \ Eloquent \ ModelNotFoundException".

dd(get_class($exception)); outputs "Illuminate\Database\Eloquent\ModelNotFoundException".

第一个是与文档类似.如何使用instanceof使其正常工作?

The first one is similar to the doc. How can I make it work using 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,您必须使用完整的类名,并且如果您的类具有名称空间,则应使用该类的完全限定类名.

To use instanceof you must use the full class name, and if your class has a namespace then you should use the fully qualified class name of the class.

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

And there is an other way to use instanceof using a short name (alias) for a given class thanks to use statement, in your case you can use it like so :

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错误处理,get_class vs instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆