Поймать разные типы исключений

У меня есть очень простая функция, чтобы проверить, существует ли Сущность в пакете:

public function checkExists($bundle, $val) { try{ $this->em->getRepository($bundle.':'.$val); }catch (MappingException $e){ return false; } return true; } 

Поэтому у меня есть следующие случаи:

 Input | Expected | Actual 'AppBundle', 'Company' | true | true 'AppBundle', 'NONEXISTANT' | false | false (MappingException caught) 'NONEXISTANT', 'Company' | false | 500 (ORMException not caught) 'NONEXISTANT', 'NONEXISTANT' | false | 500 (ORMException not caught) 

Поэтому я вижу, что проблема заключается в том, что есть разные исключения, но как я могу вернуть false для любого из случаев, когда одна часть не существует? Есть ли «общий» способ перехватывать исключения в symfony как catch (Exception $e) с use Symfony\Component\Config\Definition\Exception\Exception; не поймает его.

Есть несколько вещей, которые нужно сделать: вы можете поймать все исключения во-первых, тогда вы можете обрабатывать каждый по-другому:

 public function checkExists($bundle, $val) { try{ $this->em->getRepository($bundle.':'.$val); } catch (\Exception $e){ // \Exception is the global scope exception if ($e instanceof MappingException || $e instanceof ORMException) { return false; } throw $e; //Rethrow it if you can't handle it here. } return true; } 

Alternatevely имеют множественные уловы:

  public function checkExists($bundle, $val) { try{ $this->em->getRepository($bundle.':'.$val); } catch (MappingException $e){ return false; } catch (ORMException $e) { return false; } //Other exceptions are still unhandled. return true; } 

Если вы используете PHP 7.1 +, вы также можете:

 public function checkExists($bundle, $val) { try{ $this->em->getRepository($bundle.':'.$val); } catch (MappingException | ORMException $e){ //Catch either MappingException or ORMException return false; } //Other exceptions are still unhandled. return true; } 

Создайте Exception Listener и обработайте их там.

 class ExceptionListener { /** @var LoggerInterface */ private $logger; public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function onKernelException(GetResponseForExceptionEvent $event) { $e = $event->getException(); if ($e instanceof ValidationException) { $this->logger->notice('Validation error' , $e->getViolations()); } elseif ($e instanceof DomainException) { $this->logger->warning('Exception ' . get_class($e) , ['message' => $e->getMessage()]); $event->setResponse( new JsonResponse(['error' => $this->translator->trans($e->getOutMessage())], 400) ); } else { $event->setResponse( new JsonResponse(['error' => $this->translator->trans('http.internal_server_error')], 500) ); } } } 

Обновить services.yml

  app.exception_listener: class: Application\Listeners\ExceptionListener arguments: ['@domain.logger'] tags: - { name: kernel.event_listener, event: kernel.exception } 

Дальнейшее чтение о слушателях и событиях https://symfony.com/doc/current/event_dispatcher.html

Я не уверен, что вы должны создавать ситуации, которые вызывают исключения Mapping, когда ваше приложение отправляется.