duan0818 2019-02-18 14:08
浏览 18
已采纳

捆绑特定的异常监听器

Lets say I have 3 different bundles.

I am adding to event listeners to each bundle. When there is any exception in Bundle1, then Bundle2 and Bundle3 should not listen it.

I have tested it adding to each bundle eventlistener but when there is any error in Bundle2 then Bundle1 will listen try to handle it as well.

How to handle this situation?

if needed any code then here is my service.yaml in bundle:

kernel.listener.test1bundle.exceptionlistener:
    class: App\test1bundle\EventListener\ExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception}

and here is my exception listener:

public function onKernelException(GetResponseForExceptionEvent $event)
{
    // You get the exception object from the received event
    $exception = $event->getException();
    $message = [ 
        "errors" => [
            [
                "title" => "Internal error in test1 bundle",
                "detail" => $exception->getMessage()
            ]
        ]
    ];

    $response = new JsonResponse();
    $response->setData($message);

    $response->headers->set('Content-Type', 'application/problem+json');

    $event->setResponse($response);
}

i read that it is possible just listen controller. But in that case will controller listener listen exceptions as well?

  • 写回答

2条回答 默认 最新

  • doufan6544 2019-02-18 14:33
    关注

    What you need to do is to create different "families" of exceptions, and each event listener should decide to act or not act on the exception depending on its parentage.

    E.g. lets say that on each of your bundles you create an abstract exception:

    abstract class BundleOneException extends \Exception {}
    

    (and the same for BundleTwo and BundleThree). Now on each bundle, every exception you throw should be one extended from this one.

    Then on each listener you could do:

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
    
        if (!$exception instanceof BundleOneException) {
            return;
        }
    
        // otherwise, do your thing
    
    }
    

    All listener are listening to all exceptions, but they will only act on the appropriate exceptions.

    This is the most practical wa to handle the situation. Yes, you'd need each bundle to be consistent in the type of exceptions they throw; but throwing generic exceptions is not great practice (as demonstrated by this kind of situation).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改