Symfony messenger get retry count in handler
Asked Answered
T

1

9

I have implemented symfony messenger https://symfony.com/doc/current/messenger.html. I want to get retry count in handler class which implements MessageHandlerInterface

Messenger consumer command throws an error and retries it 5 times according to configuration. So I want to get retry count in handler so I can add some logic accordingly.

I also tried to create middleware as mentioned in this answer https://stackoverflow.com/a/61078739. But this middleware doesn't get executed.

Tristram answered 16/8, 2021 at 17:11 Comment(0)
G
2

But this middleware doesn't get executed, it may not have been configured, like:

#messenger.yaml
framework:
    messenger:
        buses:
            messenger.bus.default:
                middleware:
                    - 'App\Middleware\RetryCountMiddleware'

Also, a new stamp HandlerArgumentsStamp has appeared in Symfony 6.2, which allows you to add your own data a bit easier.

For example:

namespace App\Middleware;

use App\Contracts\RetryCountSupportInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\HandlerArgumentsStamp;
use Symfony\Component\Messenger\Stamp\RedeliveryStamp;

class RetryCountMiddleware implements MiddlewareInterface
{
    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        # Check based on interface, class, stamp or something else
        if ($envelope->getMessage() instanceof RetryCountSupportInterface) {
            $envelope = $envelope->with(new HandlerArgumentsStamp([
                'retryCount' => RedeliveryStamp::getRetryCountFromEnvelope($envelope)
            ]));
        }

        return $stack->next()->handle($envelope, $stack);
    }
}

And in handle

#[AsMessageHandler]
class YourMessageHandler
{

    public function __invoke(YourMessage $message, int $retryCount): void
    {
        #...
    }
}
Gaekwar answered 17/3, 2023 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.