gpt4 book ai didi

php - 忽略并继续处理特定的 Symfony2 kernel.exception 事件

转载 作者:行者123 更新时间:2023-12-04 16:49:26 24 4
gpt4 key购买 nike

场景:

Symfony2 项目使用主数据库和用于远程数据的辅助(远程)数据库。远程数据库可能已关闭或它们之间的连接可能被切断。在这种情况下,我仍然希望执行继续正常进行,尽管会发出远程已关闭的通知。

到目前为止,我已经在我的事件监听器中尝试过:

public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();

if (
$exception instanceof ConnectionException ||
$exception instanceof PDOException ||
$exception instanceof \PDOException ||
$exception instanceof DBALException
) {
$this->flash->flashMessage('remote_server_connection_error', array(), FlashBagUtil::TYPE_ALERT);

// $kernel = $event->getKernel();
// $request = $event->getRequest();
// $response = $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, true);
// $response->setStatusCode(Response::HTTP_OK);
// $event->setResponse($response);

$event->stopPropagation();
echo 'works';
}
}

如果我取消注释响应部分,我会按预期重新调整页面,但状态为 500,而不是我明确设置的 200。 “works”得到回应,因此事件部分工作正常。

在 Symfony2 kernel.exception 监听器中处理异常并忽略其余请求的正确方法是什么?

非常感谢

最佳答案

documentation 中所述,对于 kernel.exception 事件:

As Symfony ensures that the Response status code is set to the most appropriate one depending on the exception, setting the status on the response won't work. If you want to overwrite the status code (which you should not without a good reason), set the X-Status-Code header

所以你必须设置这个标题:

$response->headers->set('X-Status-Code', Response::HTTP_OK);

关于php - 忽略并继续处理特定的 Symfony2 kernel.exception 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com