【问题标题】:Access Request Object in Error Handler Laravel错误处理程序 Laravel 中的访问请求对象
【发布时间】:2016-01-25 15:28:53
【问题描述】:

在我的 Laravel 5.2 项目中,我有一个中间件可以愉快地存储对数据库或文件的请求和响应。 在那里我序列化/json_encode $request 对象用于记录所有发生的事情。 (cookies、输入、文件、标题...)

我需要创建一个错误处理程序,它将使用整个请求对象将有关请求的所有内容包含到报告电子邮件中。但是ExceptionHandler::report()不接受Request作为参数。

【问题讨论】:

    标签: php laravel laravel-5.2


    【解决方案1】:

    Laravel 5.2 提供了the helper method request(),适用于这个用例:

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        $request = request();
    
        parent::report($exception);
    }
    

    【讨论】:

      【解决方案2】:

      在 App\Exceptions\Handler.php 和 render 方法中确实有请求作为参数。 在这里,您可以触发一个事件以将内容存储在会话或数据库中。

      例如:

      public function render($request, Exception $e)
          {
              if ($e instanceof HttpException) {
                  if ($e->getStatusCode() == 403) {
                      Event::fire(new UserNotAllowed($request));
                      return redirect()->to("/home");
                  }
                  if ($e->getStatusCode() == 404) {
                      if (Auth::guest()) {
                          return redirect()->to("/");
                      }
                  }
              }
              if ($e instanceof ModelNotFoundException) {          
                  $e = new NotFoundHttpException($e->getMessage(), $e);
              }
              return parent::render($request, $e);
          }
      

      更多信息here.

      【讨论】:

      • 将异常呈现到 HTTP 响应中。 这就是描述的内容。将渲染用于此类操作是否正确?
      • 这可能是您在错误处理程序中捕获请求的唯一方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 2017-04-28
      • 2012-03-09
      相关资源
      最近更新 更多