Separation of transactions between two different buses in symfony messenger when error occurs in the first one

Viewed 348

Let's say we have the following code:

try {
        $message = new CreateSomething($data);
        $this->messageBus->dispatch($message);
    } catch (RuntimeException $exception) {
        $failNotification = new CreateFailedNotification($data);
        $this->eventBus->dispatch($failNotification);

        throw $exception;
    }

Both of the buses have set DoctrineTransactionMiddleware. Let's assume that during process handlers within messageBus we persist some entities but exception occurs - DoctrineTransactionMiddleware provides rollback transactions in that situation, so later we land in the catch block in the above code. In the eventBus everything is processed fine, so the transaction which is created in the eventBus is committed successfully, but entityManager has also entities which have persisted during messageBus - so finally these entities are also saved to DB what is unwanted behavior.

I've read in doctrine documentation that

When using explicit transaction demarcation and an exception occurs, the transaction should be rolled back immediately and the EntityManager closed by invoking EntityManager#close()

DoctrineTransactionMiddleware doesn't do that - I have to explicitly execute close() method in catch block before executing eventBus dispatch - then I rid off unwanted entities from messageBus. Maybe I understand wrong the idea and it just works like that OR DoctrineMiddleware misses execute close() method. IMO DoctrineTransactionMiddleware should provide such execution without developer intervention.

0 Answers
Related