在 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);
}
关于laravel-5.4 - Laravel 错误处理,get_class 与 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44927794/