shi*_*hin 4 laravel-exceptions laravel-5.4
在 app/Exceptions/Handler.php 中的以下代码中,第一个不起作用,但第二个起作用。
dd(get_class($exception)); 输出“Illuminate\Database\Eloquent\ModelNotFoundException”。
第一个类似于 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);
}
Run Code Online (Sandbox Code Playgroud)
要使用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);
}
Run Code Online (Sandbox Code Playgroud)