Messenger处理程序的自定义异常

时间:2019-04-07 11:11:37

标签: symfony

我尝试使用Symfony 4.3.0-dev版本从Messenger组件中获取一些新功能。我的命令总线在同步模式下工作。

在升级之前,我可以轻松地从处理程序返回我的自定义异常ConflictException。但是对于4.3.0-dev,我得到了Symfony \ Component \ Messenger \ Exception \ HandlerFailedException。如何再次返回我的自定义异常?

3 个答案:

答案 0 :(得分:0)

如您在CHANGELOG上所见,在4.3版中引入了BC中断。 在我的应用程序中,我正在捕获异常,并通过添加以下代码来解决:

if ($exception instanceof HandlerFailedException) {
    $exception = $exception->getPrevious();
}

答案 1 :(得分:0)

以下是与此更改相关的文章:here

更改在Symfony 4.3版本中仍然存在。

答案 2 :(得分:0)

从Symfony 4.3开始,如果处理程序抛出任何异常,它将包装在Symfony\Component\Messenger\Exception\HandlerFailedException中。

这在变更日志中反映为here

  

[BC BREAK]如果一个或多个处理程序失败,将引发HandlerFailedException异常。

在您要处理同步传输并且要处理原始异常的地方,您可以执行类似于Api-Platform在this DispatchTrait中所做的操作:

namespace App\Infrastructure\Messenger;

use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\MessageBusInterface;
use Throwable;

trait DispatchTrait
{

    private ?MessageBusInterface $messageBus;

    /**
     * @param object|Envelope $message
     * @return Envelope
     * @throws Throwable
     */
    private function dispatch($message): ?Envelope
    {
        try {
            return $this->messageBus->dispatch($message);
        } catch (HandlerFailedException $e) {
            while ($e instanceof HandlerFailedException) {
                /** @var Throwable $e */
                $e = $e->getPrevious();
            }

            throw $e;
        }
    }
}

(此版本没有向后兼容性,并且取消了MessageBus检查,因为我只用于我控制的内部应用程序。)

在发送消息的任何类中,您都可以这样做:

class FooController
{
    use DispatchTrait;

    public function __construct(MessageBusInterface $messageBus) {
        $this->messageBus = $messageBus;
    }

    public function __invoke(Request $request)
    {
        // however you create your message
        $command = Command::fromHttpRequest(); 

        try {
                $this->dispatch($command);
        }
        catch (ConflictException $e) {
            // deal with the original exception
        }
    }
}
相关问题