【问题标题】:Laravel - One view for all possible errorsLaravel - 所有可能错误的一个视图
【发布时间】:2016-07-29 08:15:22
【问题描述】:

所以我想只用一个视图来涵盖所有可能的和意外的错误(如 401、404、500)。我希望在所有可能的错误上都显示相同的视图。我想出了一个解决方案——复制/粘贴相同的代码,然后用不同的错误代码命名视图。但这似乎僵硬和错误。有没有更好的方法来实现这一点?

【问题讨论】:

    标签: php laravel error-handling


    【解决方案1】:

    在文件 app/Exceptions/Handler.php 中,您可以更改抛出异常时发生的情况。特别是其中有一个 render 方法,您可以使用它来捕获应用程序中的所有异常。

    public function render($request, Exception $e)
    {
        // Handle your error here. Perhaps you can show a view
        // when a condition is met. Anything that isn't caught
        // here will be handled by Laravel with the
        // parent::render call below
    
        return parent::render($request, $e);
    }
    

    parent::render($request, $e) 是 Laravel 通常显示它的异常/糟糕页面的地方。因此,通过覆盖此方法,您可以捕获所有应用程序错误,包括 404、401 等。

    【讨论】:

      【解决方案2】:

      实现此效果的更简洁的方法是修改Laravel's exception handler

      修改 App\Exceptions\Handler 以捕获每个错误并返回您共享的自定义错误页面。

      /**
       * Render an exception into an HTTP response.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Exception  $e
       * @return \Illuminate\Http\Response
       */
      public function render($request, Exception $e)
      {
          if ($e instanceof NotFoundHttpException) {
              return response()->view('errors.custom', [], 404);
          }
      
          return parent::render($request, $e);
      }
      

      可能需要进行一些自定义才能完全满足您希望将数据传递到共享自定义视图的内容和方式。

      【讨论】:

        【解决方案3】:

        将错误代码传递给处理程序上的视图,并在页面上显示代码,使用开关根据错误代码处理所有消息。

        【讨论】:

          【解决方案4】:

          您可以创建一个唯一的视图(默认为 404 错误),在代码中使用 try catch 来捕获其他错误并使用参数调用此视图,以便您可以将 404 默认错误更改为其他错误。

          【讨论】:

            猜你喜欢
            • 2019-12-26
            • 1970-01-01
            • 2016-09-17
            • 2014-06-26
            • 2014-08-13
            • 1970-01-01
            • 2021-06-24
            • 2017-08-04
            • 1970-01-01
            相关资源
            最近更新 更多