2 years ago

#32695

test-img

GeorgeR

Mediatr - when throwing an exception from command handler app crashes and the exception remains unhandled

public class Manager(IMediator mediatr)
{
    try
    {
        mediatr.Send(new DummyCommand());
    }
    catch (Exception ex)
    {
         // Never gets called!
    }
}

public class DummyCommand : IRequest<DummyResponse>
{
}

public class DummyCommandHandler : IRequestHandler<DummyCommand, DummyResponse>
{
    public async Task<DummyResponse> Handle(DummyCommand
               command, CancellationToken cancellationToken)
    {
        throw new Exception("Dummy Error");
    }
}

Why doesn't the exception get propagated to the calling code? I get unhandled exception in ExceptionDispatchInfo class of the System.Runtime.ExceptionServices namespace that the exception is unhandled

Decompiled IL:

    // When a framework needs to "Rethrow" an exception on a thread different (but not necessarily so) from
    // where it was thrown, it should invoke this method against the ExceptionDispatchInfo
    // created for the exception in question.
    //
    // This method will restore the original stack trace and bucketing details before throwing
    // the exception so that it is easy, from debugging standpoint, to understand what really went wrong on
    // the original thread.
    [DoesNotReturn]
    [StackTraceHidden]
    public void Throw()
    {
        // Restore the exception dispatch details before throwing the exception.
        _exception.RestoreDispatchState(_dispatchState);
        throw _exception;
    }

Is it still possible to catch the exception (I assume command handler handle is executed on a different thread), or should the error be captured in the response somehow?

c#

.net-core

mediatr

0 Answers

Your Answer

Accepted video resources