【问题标题】:Can't catch \InvalidArgumentException in Symfony2 Controller无法在 Symfony2 控制器中捕获 \InvalidArgumentException
【发布时间】:2017-02-23 18:15:57
【问题描述】:

我发现了很多关于在 Symfony2 中捕获异常的问题,但似乎没有一个答案适用于我的情况。

我试图在我的控制器中调用$this->forward(),它会抛出一个我无法捕捉到的\InvalidArgumentException。我只是得到了500错误页面。

500 Internal Server Error - InvalidArgumentException 

我试图捕捉这个异常:

try {
    $response = $this->forward('FooBundle:Foo:bar', ['foo' => 'bar']);
} catch (\InvalidArgumentException $ex) {
    error_log($ex->getMessage());
} catch (\Exception $ex) {
    // this doesn't work either
}

这个异常是 Symfony 在第 65 行的Symfony\Component\HttpKernel\Controller\ControllerResolver 中抛出的:

throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));

这似乎是一个 SPL 异常。它出现就好像我正确地抓住了它。那么缺少什么?

注意:这是在我的开发环境中,如果与它有关的话。


有趣的是,将 this 放在我的控制器中确实有效

try {
    throw new \InvalidArgumentException('Fake Exception');
} catch (\InvalidArgumentException $ex) {
    // do nothing
}

【问题讨论】:

  • 糟糕,我什至没有注意到 500 错误是对 forward() 的调用的实际响应。也许应该删除 Q...

标签: php symfony exception-handling


【解决方案1】:

你试过了吗:

$response = $this->forward('FooBundle:Foo:bar');

我认为这是正确的,除非您的控制器需要参数,然后您将参数放入数组中。你能试试吗?不过,我不确定这是否能解决问题。

【讨论】:

  • 有参数,我只是没有将它们包含在上面的示例代码中。但这不是问题。不过还是谢谢!
【解决方案2】:

好的,所以 500 错误是转发的响应正文 - 从技术上讲 工作的。对$this->forward() 的调用不是问题,问题是我显示响应正文没有先检查

通过这样做修复它:

$response = $this->forward('FooBundle:Foo:bar', ['foo' => 'bar']);
$content  = (500 !== $response->getStatusCode()) 
    ? $response->getContent()
    : '';

return new Response($content);

注意:try {} catch (\Exception $e) {} 完全没有必要,实际上对此毫无意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多