【问题标题】:Why error handling is not working in Laravel为什么错误处理在 Laravel 中不起作用
【发布时间】:2020-03-10 01:09:15
【问题描述】:

我已在.env 文件上将调试设置为 true。正确添加了异常,但是当我传递无效或在我的数据库中不存在时,它向我显示 404 错误,但在这里我放置了自定义错误处理值。这是我的代码。 (我也把“使用期望;”放在最上面,所以不需要 \Expectation)

public function show($id)
    {
        //only one author with id
        try
        {
            $event = Event::with('eventCategory')->findOrFail($id);
            return new EventsResource($event);
            //return one author
        }
        catch(Expectation $e)
        {   
            report($e);
            return response()->json(['status'=> false, 'message'=>'invalid data'],200);

        }
    }

【问题讨论】:

  • 这能回答你的问题吗? laravel routing and 404 error
  • 在 catch 块中它的异常不是期望
  • 你可以使用 } catch (\Exception $ex) { 如果你在 PHP7 上我会建议更好地使用 } (\Throwable $ex) {

标签: php laravel laravel-5


【解决方案1】:

你的意思是例外吗?因为在你的问题中它是期望......

【讨论】:

    【解决方案2】:

    正如@user3532758 所暗示的那样,您可能想要捕捉基础Exception 而不是Expectation

    还要确保您从根命名空间引用Exception,假设您显示的代码在控制器中:

    try {
        ...
    } catch (\Exception $e) {
        ...
    }
    

    PHP Manual - Classes - Exception

    【讨论】:

    • 真的很抱歉!!这是一个愚蠢的错误。我是 laravel 的新手,但这不是我应该正确检查的问题。
    猜你喜欢
    • 2020-08-17
    • 2021-10-29
    • 2022-01-03
    • 2020-07-02
    • 2021-10-31
    • 2021-12-02
    • 2011-06-24
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多