捕捉不同类型的异常

3

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

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;无法捕获它。

可能是Catching multiple exception types in one catch block的重复问题。 - jkucharovic
1
你真的不想依赖异常来处理这种情况。看一下Doctrine的元数据。特别是:$em->getClassMetadata($entityClassName); - Cerad
2个回答

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

或者使用多个catch语句:

 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
创建异常监听器并在那里处理它们。
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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接