Catching database exceptions in Symfony2(在 Symfony2 中捕获数据库异常)
问题描述
我遇到了一个无法缩小范围的随机问题.有时,我会在 Symfony2 应用程序中收到以下错误:
I've got a random problem that I can't narrow down. Occasionally, I will get the following error in a Symfony2 application:
未捕获的异常:驱动程序中发生异常:SQLSTATE[08004] [1040] 连接太多 {"type":1,"file":"/var/www/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line":115,"level":30709
Uncaught Exception: An exception occured in driver: SQLSTATE[08004] [1040] Too many connections {"type":1,"file":"/var/www/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line":115,"level":30709
我想设置一个应用程序范围的侦听器来捕获 PDOException
并记录一些信息.我怎样才能挂钩到 Symfony 只捕获 PDOException
?
I would like to setup an application-wide listener to catch the PDOException
and log some information. How can I hook into Symfony to only catch PDOException
?
推荐答案
您需要创建自定义异常侦听器.它将侦听所有异常,但您将在其中指定类型检查.
You need to create custom exception listener. It will listen to all exceptions, but you will specify type check inside it.
在您的 services.yml
中,您需要指定侦听器:
In your services.yml
you need to specify listener:
kernel.listener.your_pdo_listener:
class: AcmeAppBundleEventListenerYourExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onPdoException }
现在你需要创建这个类:
Now you need to create this class:
你的异常监听器:
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
class YourExceptionListener
{
public function onPdoException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof PDOException) {
//now you can do whatever you want with this exception
}
}
}
检查文档 如何创建事件监听器
这篇关于在 Symfony2 中捕获数据库异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Symfony2 中捕获数据库异常


- PHP - if 语句中的倒序 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01