2017-07-05 41 views
1

在下面的代码在应用程序/异常/ Handler.php,第一个不工作,但第二个一样。Laravel错误处理,get_class VS的instanceof

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

尝试添加\像这样的:'如果($例外的instanceof \照亮\数据库\雄辩\ ModelNotFoundException){// ...}',看看它是否有效! – Maraboc

+0

不,它也不起作用。 – shin

+1

尝试添加'使用Illuminate \ Database \ Eloquent \ ModelNotFoundException作为ModelNotFoundException;'然后'if($ exception instanceof ModelNotFoundException){// ...}' – Maraboc

回答

1

要使用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); 
}