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

Hug*_*ugo 3 php error-handling symfony doctrine-orm

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

我不想显示错误 500,而是想显示如下消息:“您无法删除它,因为某些项目已链接到它”

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

cha*_*asr 5

您可以实现一个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);   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将其声明为服务:

// 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"
Run Code Online (Sandbox Code Playgroud)

使您的模板显示会话消息:

// twig
{% for flashMessage in app.session.flashbag.get('error') %}
    {{ flashMessage }} 
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

编辑

如果您想在特定操作上拦截此错误,您可以这样做:

try {
    $em->flush();
} catch (\Exception $e) {
    $errorMessage = $e->getMessage();
    // Add your message in the session
    $this->get(‘session’)->getFlashBag()->add('error', 'PDO Exception :'.$errorMessage);   
}
Run Code Online (Sandbox Code Playgroud)