'onKernelException', ]; } public function onKernelException(ExceptionEvent $event): void { $exception = $this->findUniqueConstraintViolation($event->getThrowable()); if (!$exception) { return; } $event->setResponse(new JsonResponse( [ 'success' => false, 'error' => 'nom duplique', ], JsonResponse::HTTP_CONFLICT )); } private function findUniqueConstraintViolation(Throwable $throwable): ?UniqueConstraintViolationException { for ($current = $throwable; null !== $current; $current = $current->getPrevious()) { if ($current instanceof UniqueConstraintViolationException) { return $current; } } return null; } }