Symfony + Doctrine - 在完整性约束错误时定义错误消息

时间:2016-02-18 15:53:08

标签: php symfony error-handling doctrine-orm

当我尝试删除项目时出现完整性约束错误时,我正在尝试显示一条很好的错误消息。

而不是出现错误500,我只想显示如下消息: “你不能删除它,因为有些项链接到它”

我一直在寻找,但我总是找到“如何解决这个错误”的解决方案。我不会解决它,我只想捕获错误,就像带有消息参数的@UniqueEntity注释一样。

1 个答案:

答案 0 :(得分:4)

您可以实施一个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"

让模板显示会话消息:

// 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);   
}