【问题标题】:Laravel 5 package exceptions not firing Hander's render methodLaravel 5 包异常未触发 Hander 的渲染方法
【发布时间】:2015-05-07 21:06:34
【问题描述】:

我正在开发一个包并使用 Orchestra/Testbench 包进行单元测试。

我正在尝试编写一个 PHPUnit 测试,以验证在引发异常时响应是否正确。在我的存储库中,我抛出以下异常:

use Acme\Common\Exceptions\ValidationException;
...
throw new ValidationException($validator);

我已经在包的服务提供者中注册了处理程序类:

$this->app->singleton('Illuminate\Contracts\Debug\ExceptionHandler', 'Acme\Common\Exceptions\Handler');

但是 Handler 类中的 render() 方法没有被触发。这是 render() 方法:

public function render($request, Exception $e)
{
    if ($e instanceof \Acme\Common\Exceptions\ValidationException) {

        $message = implode(' ', array_flatten($exception->getMessages()->toArray()));

        $response = array('errorCode' => $exception->getCode());

        return \Response::make($response, 400);
    }

    return parent::render($request, $e);
}

相反,我只得到通用异常方法:

Acme\Common\Exceptions\ValidationException: {"key":["The key field is required."]}

我什至在 render() 方法的开头放了一个 dd() ,但没有。我是否缺少 Orchestra Testbench 的某种设置?

【问题讨论】:

    标签: php phpunit laravel-5


    【解决方案1】:

    您是否偶然覆盖了此类中的构造函数?我遇到了完全相同的问题(也试图捕获 ValidationException),但我没有意识到我搞砸了构造函数。可能发生的事情是导致发生未捕获的异常(因为它发生在您的异常处理程序中!)。在我的例子中,我覆盖了构造函数,这意味着父类没有注入 Log 类,这导致在触发渲染方法之前抛出异常并停止事情。

    【讨论】:

      【解决方案2】:

      您通过变量“$e”注入异常类,但在您的方法中调用变量“$exception”。

      由于未设置$exception-变量,您应该使用您的$e-变量。

      public function render($request, Exception $e)
      {
          if ($e instanceof \Acme\Common\Exceptions\ValidationException) {
      
              $message = implode(' ', array_flatten($e->getMessages()->toArray()));
      
              $response = array('errorCode' => $e->getCode());
      
              return \Response::make($response, 400);
      
          }
      
          return parent::render($request, $e);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-02
        • 2019-05-12
        • 2023-03-22
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        • 2015-05-25
        • 2015-01-08
        相关资源
        最近更新 更多