laravel - 在 Laravel 5 上全局捕获 ModelNotFoundException
问题描述
我试图从 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
);
}
推荐阅读
- swift - UIPasteboard 在后台返回 nil
- javascript - 模态关闭后显示按钮
- java - 让斯坦福 NLP 识别具有多个单词的命名实体
- scala - 如何在 playframework 模板中显示换行符?
- mysql - 如何优化这个 MYSQL 查询?(获得结果的巨大延迟)
- css - 在旧的 Mozilla 版本中隐藏滚动条,保留滚动条
- docker - 在 Docker 服务中创建 Docker 服务
- java - Android Studio - 带有通知通道的奥利奥持续通知
- android - 获取用户输入到 NotificationCompiler
- docker - .Net核心角度模板dockerfile错误