在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);
}
有时会重新抛出$异常,所以尽量使用
$exception->getPrevious() insanceof XXX
要么
get_class($exception->getPrevious()) == 'XXX'