Laravel错误处理,get_class vs instanceof



在 app/Exceptions/Handler.php 中的以下代码中,第一个不起作用,但第二个不起作用。

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

第一个类似于文档。如何使用instanceof使其工作?

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

若要使用instanceof,必须使用完整的类名,如果您的类具有命名空间,则应使用该类的完全限定类名。

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

use IlluminateDatabaseEloquentModelNotFoundException as ModelNotFoundException; // on top of course :) 
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error'=>['message'=>'Resouce not found']], 404);
}

有时会重新抛出$exception,所以尝试使用

$exception->getPrevious() instanceof XXX

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

最新更新