【发布时间】:2017-12-09 05:09:17
【问题描述】:
在 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);
}
【问题讨论】:
-
尝试像这样添加 \ :
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { //... }看看它是否会起作用! -
不,它也不起作用。
-
尝试在顶部添加
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;然后if ($exception instanceof ModelNotFoundException) { //... } -
是的,它奏效了。您能否将其放入答案中,以便我将其作为解决方案打勾?谢谢。
标签: laravel-5.4 laravel-exceptions