如何 return 为 `Illuminate\Support\ItemNotFoundException` 自定义响应?
How to return custom response for `Illuminate\Support\ItemNotFoundException`?
在我的控制器中,我使用方法 firstOrFail()
进行数据库查询 Eloquent。在调试模式下,我收到内容为 Illuminate\Support\ItemNotFoundException
.
的 Laravel 错误消息
但是,我想 return redirect()
或 back()
而不是显示此错误屏幕。我该怎么做?
而不是 firstOrFail()
使用 first()
并使用条件重定向回来,例如:
$item = Item::where('slug', $slug)->first();
if (! $item) {
return redirect()->back();
}
使用php try catch来覆盖错误捕获的行为,
try {
// your functional code
} catch (Illuminate\Support\ItemNotFoundException $exception ) {
//your redirect command , the code here will be executed if there is an exception with type ItemNotFoundException
}
如果你想捕获所有错误,你需要使用一般异常class,它是所有异常的父类
try {
// your functional code
} catch (\Exception $exception) {
//your redirect command , the code here will be executed if there is any exception
}
如果您想获取异常消息以记录它或进行任何自定义,您可以使用方法:getMessage()
,在我们的例子中将是 $exception->getMessage()
在我的控制器中,我使用方法 firstOrFail()
进行数据库查询 Eloquent。在调试模式下,我收到内容为 Illuminate\Support\ItemNotFoundException
.
但是,我想 return redirect()
或 back()
而不是显示此错误屏幕。我该怎么做?
而不是 firstOrFail()
使用 first()
并使用条件重定向回来,例如:
$item = Item::where('slug', $slug)->first();
if (! $item) {
return redirect()->back();
}
使用php try catch来覆盖错误捕获的行为,
try {
// your functional code
} catch (Illuminate\Support\ItemNotFoundException $exception ) {
//your redirect command , the code here will be executed if there is an exception with type ItemNotFoundException
}
如果你想捕获所有错误,你需要使用一般异常class,它是所有异常的父类
try {
// your functional code
} catch (\Exception $exception) {
//your redirect command , the code here will be executed if there is any exception
}
如果您想获取异常消息以记录它或进行任何自定义,您可以使用方法:getMessage()
,在我们的例子中将是 $exception->getMessage()