我试图从app \ Exceptions \ Handler类全局捕获ModelNotFoundException,因此不必在每个控制器上检查它。
但它不起作用,虽然它在控制器内工作正常:
try {
$asset = Asset::findOrFail($asset_id);
} catch (Exception $e) {
if ($e instanceof ModelNotFoundException)
{
$model = explode('\\', $e->getModel());
return $this->respondWithRecordNotFound(end($model) . ' record not found');
}
return $this->respondWithGeneralError($e->getMessage());
}
应用程序\例外\处理程序:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException)
{
$model = explode('\\', $exception->getModel());
return $this->respondWithRecordNotFound(end($model) . ' record not found');
}
return parent::render($request, $exception);
}
我不确定你的respondWithRecordNotFound
在做什么。我想这个问题可能就在那里。
无论如何,我只是试了一下,这对我有用。在App\Exceptions\Handler.php@render
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->view(
'errors.404',
["message" => $e->getModel() . ' record not found'],
404
);
}
只需确保在Handler.php中添加了用法
use \Illuminate\Database\Eloquent\ModelNotFoundException;