当我尝试删除项目时出现完整性约束错误时,我试图显示一条友好的错误消息。
我不想显示错误 500,而是想显示如下消息: “你不能删除它,因为有些项目链接到它”
我已经搜索了一段时间,但总能找到关于“如何解决此错误”的解决方案。我不会不解决它,我只是想捕获错误,就像带有消息参数的 @UniqueEntity
注释一样。
最佳答案
您可以实现一个 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"
使您的模板显示 session 消息:
// twig
{% for flashMessage in app.session.flashbag.get('error') %}
{{ flashMessage }}
{% endfor %}
编辑
如果你想在特定的操作上拦截这个错误,你可以这样做:
try {
$em->flush();
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
// Add your message in the session
$this->get(‘session’)->getFlashBag()->add('error', 'PDO Exception :'.$errorMessage);
}
关于php - Symfony + Doctrine - 定义完整性约束错误时的错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486188/