jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
10.91k stars 1.16k forks source link

Added behavior exceptions not triggering actions/handlers #923

Closed RazvanRus97 closed 1 year ago

RazvanRus97 commented 1 year ago

Hello, I have an issue where the exceptions that are being thrown from the added behavior do not trigger the exception Actions. The exception is not being handled any other way.

Currently, if the exception is being thrown from the command handler the exception action is executed correctly. What I am doing at the moment:

public record MyCommand(MyPayload Payload) : IRequest;

public class AddedBehavior: IPipelineBehavior<MyCommand, Unit>
{
    public async Task<Unit> Handle(MyCommand request, RequestHandlerDelegate<Unit> next, CancellationToken cancellationToken)
    {
        throw new NullReferenceException();
    }
}

public class EventHandler: IRequestHandler<MyCommand>
{
   public async Task Handle(MyCommand request, CancellationToken cancellationToken) => await DoStuff();
}

public class ExceptionAction: AsyncRequestExceptionAction<MyCommand>
{
    protected override async Task Execute(MyCommand request, Exception exception, CancellationToken cancellationToken)
    {
        // update db record using fields from MyPayload
    }
}

//Dependency Injection:
        services.AddMediatR(cfg =>
        {
            cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
            cfg.AddBehavior<IPipelineBehavior<MyCommand, Unit>, AddedBehavior>();
        });

I tried to look through the wiki for answers to my problem but I don't seem to be able to figure out what I am missing. Any suggestion is greatly appreciated

jbogard commented 1 year ago

What version?

jbogard commented 1 year ago

I was able to reproduce this locally. The exception behaviors need to be the first ones registered, before processors and custom behaviors. I'll push out a fix today.