Symfony +主义-当完整性约束错误时定义错误消息 [英] Symfony + Doctrine - Define an error message when integrity constraint error
问题描述
当我尝试删除项目时出现完整性约束错误时,我试图显示一条很好的错误消息。
I'm trying to display a nice error message when an integrity constraint error shows up while I try to delete an item.
而不是出现严重错误500 ,我只想显示一条消息:
您无法删除它,因为某些项目已链接到它。
Instead of having a bad error 500, I just want to display a message like : "You can't delete this because some items are linked to it"
我一直在寻找一个一会儿,但我总能找到如何解决此错误的解决方案。我不会解决它,我只想捕捉错误,就像带有消息参数的 @UniqueEntity
注释一样。
I have been searching for a while but I always find solution on "how to solve this error". I don't won't to solve it, I just want to catch the error, just like a @UniqueEntity
annotation with a message argument.
推荐答案
您可以实现 EventListener
来监听 PDOException
:
// src/CM/PlatformBundlee/EventListener/PDOExceptionResponseListener.php
namespace CM\PlatformBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\DBAL\Driver\PDOException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class PDOExceptionResponseListener
{
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelResponse(GetResponseForExceptionEvent $event)
{
$request = $event->getRequest();
$exception = $event->getException();
$message = $exception->getMessage();
// Listen only on the expected exception
if (!$exception instanceof PDOException) {
return;
}
// You can make some checks on the message to return a different response depending on the MySQL error given.
if (strpos($message, 'Integrity constraint violation')) {
// Add your user-friendly error message
$this->session->getFlashBag()->add('error', 'PDO Exception :'.$message);
}
}
}
将其声明为服务:
// app/config/services.yml
services:
acme.kernel.listener.pdo_exception_response_listener:
class: CM\PlatformBundle\EventListener\PDOExceptionResponseListener
tags:
- {name: kernel.event_listener, event: kernel.exception, method: onKernelResponse}
arguments:
session: "@session"
使您的模板显示会话消息:
Make your template displaying session messages :
// twig
{% for flashMessage in app.session.flashbag.get('error') %}
{{ flashMessage }}
{% endfor %}
编辑
如果要在特定操作上拦截此错误,则可以执行以下操作:
If you want intercept this error on a specific action, you can do this :
try {
$em->flush();
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
// Add your message in the session
$this->get(‘session’)->getFlashBag()->add('error', 'PDO Exception :'.$errorMessage);
}
这篇关于Symfony +主义-当完整性约束错误时定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!