我想知道什么是处理Symfony应用程序中MySQL异常的最佳方法,更不用说了,例如,来自正常环境(不是dev)的一种方法:
Oops! An Error Occurred The server returned a "500 Internal Server Error".
在_dev中的翻译如下:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '343434' for key 'rut'
您如何处理此类错误,以便向最终用户或更友好的用户显示消息?
最佳答案
最好的选择是制作一个自定义错误页面,并有选择地创建一个自定义错误处理程序以提醒您该错误。
首先,创建一个自定义错误页面,只需在/path/to/project/config/error/error.html.php
中创建一个文件。 Symfony将自动使用您的错误页面而不是错误页面(如果存在)。
如果您想提高一点,可以添加一个事件侦听器来处理未捕获的异常。为此,请编辑/path/to/project/config/ProjectConfiguration.class.php
并添加一个侦听器,如下所示:
class ProjectConfiguration extends sfProjectConfiguration
{
public function setup()
{
//...
$this->dispatcher->connect('application.throw_exception', array($this, 'listenToException'));
}
public function listenToException(sfEvent $event)
{
$handler = new myExceptionHandler($event);
$handler->doSomethingHere();
}
}
然后,您要做的就是创建自己的
myExceptionHandler
类,除了sfEvent $event
参数。您可以在此处执行任何操作,我更喜欢向自己发送电子邮件,告诉我发生了错误。这是一个简短的示例:
class myExceptionHandler
{
protected $event;
public function __construct(sfEvent $event)
{
$this->event = $event;
}
protected function getMailer()
{
return sfContext::getInstance()->getMailer();
}
public function notify()
{
$subject = 'Uncaught Exception';
$body = $this->event->getSubject();
$mailer = $this->getMailer();
$mailer->composeAndSend('root@yourserver.com', 'you@youremail.com', $subject, $body);
}
}
在此示例中,您只需从项目配置中调用
$handler->notify()
,它将通过电子邮件向您发送堆栈跟踪。您还可以包括其他信息,例如$_SERVER
变量等。
关于php - 处理来自Symfony应用程序的MySQL错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17048132/