当前位置: 动力学知识库 > 问答 > 编程问答 >

symfony2 - Recovering from exceptions in PHP/Symfony

问题描述:

I have made a simple command-line tool with Symfony2 which calls a service which throws a UniverseException in case of error. Sort of like this;

# /src/AppBundle/Command/UniverseCommand.php

class UniverseCommand extends ContainerAwareCommand

{

protected function execute(InputInterface $input, OutputInterface $output)

{

if ( 1 == 2 )

throw new UniverseException('Strange things are afoot');

}

}

I also added a CommandExceptionListener which can recover my application if a MyAppBundleException is thrown.

# /src/AppBundle/EventListener/CommandExceptionListener.php

class CommandExceptionListener

{

public function onConsoleException(ConsoleExceptionEvent $event)

{

if ($exception instanceof UniverseException) {

// Reboot the universe

// Continue existence..?

}

}

}

It works great!

But now I'd like to run the command as a daemon using the daemonizable-command bundle. If my service throws an exception, execution is stopped and that makes for a terrible daemon!

My app has already handled this type of exception. Is there any way to recover from it and allow my daemon to continue executing?

EDIT:

I tried adding a try/catch in the command like so..

# /src/AppBundle/Command/UniverseCommand.php

class UniverseCommand extends ContainerAwareCommand

{

protected function execute(InputInterface $input, OutputInterface $output)

{

try{

if ( 1 == 2 )

throw new UniverseException('Strange things are afoot');

}catch(\Exception $e){

echo 'The universe behaved badly but I rebooted it.';

}

}

}

It catches the exception and the daemon continues! But now, of course, my event listener isn't firing and the exception isn't being handled properly.

分享给朋友:
您可能感兴趣的文章:
随机阅读: