捕获不同的异常类型

时间:2017-07-28 11:35:11

标签: php symfony exception-handling try-catch

我有一个非常简单的函数来检查实体是否存在于包中:

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?有没有"一般"在catch (Exception $e) use Symfony\Component\Config\Definition\Exception\Exception;中使用{{1}}来捕获symfony中的异常的方法无法捕捉到它。

2 个答案:

答案 0 :(得分:3)

有几件事要做: 您可以先捕获所有异常,然后以不同的方式处理每个异常:

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

另外还有多次捕获:

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

答案 1 :(得分:1)

创建异常侦听器并在那里处理它们。

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

我不确定您是否应该在应用程序发布时创建抛出映射异常的情况。

相关问题