【问题标题】:How to return custom response for `Illuminate\Support\ItemNotFoundException`?如何为“Illuminate\Support\ItemNotFoundException”返回自定义响应?
【发布时间】:2021-11-11 05:38:32
【问题描述】:

在我的控制器中,我使用方法firstOrFail() 使用Eloquent 进行数据库查询。在调试模式下,我收到一条 Laravel 错误消息,内容为 Illuminate\Support\ItemNotFoundException

但是,我想返回redirect() 或mabye back(),而不是显示此错误屏幕。我该怎么做?

【问题讨论】:

  • 你应该使用 first() 而不是 firstOrFail() 然后再试一次

标签: php laravel error-handling


【解决方案1】:

使用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 
            }

如果你想捕获所有错误,你需要使用General Exception类,它是所有异常的父类

          try {
            // your functional code
            } catch (\Exception $exception) {
            //your redirect command , the code here will be executed if there is any exception 
            }

如果你想获取异常消息来记录它或任何自定义,你可以使用方法:getMessage(),在我们的例子中是$exception->getMessage()

【讨论】:

  • 你应该添加一些解释,以便其他人学习。
  • 我一定会编辑的
【解决方案2】:

而不是firstOrFail() 使用first() 并使用条件重定向回来,例如:

$item = Item::where('slug', $slug)->first();

if (! $item) {
    return redirect()->back();
}

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2021-01-08
    • 2017-03-26
    • 2021-05-10
    • 2021-07-13
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多