Laravel error handling, get_class vs instanceof

给你一囗甜甜゛ 提交于 2019-12-11 03:21:39

问题


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

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

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

回答1:


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.

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



回答2:


Sometimes an $exception is rethrown, so try to use

$exception->getPrevious() instanceof XXX

or

get_class($exception->getPrevious()) == 'XXX'


来源:https://stackoverflow.com/questions/44927794/laravel-error-handling-get-class-vs-instanceof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!