Custom Exception Handling

Component: NServiceBus
NuGet Package NServiceBus (5.x)

The IManageMessageFailures interface allows managing of both serialization exceptions as well as other unhandled exceptions thrown when handling a message. To ensure message loss does not happen, any unhandled exception thrown in the IManageMessageFailures interface will cause process hosting NServiceBus to terminate and effectively rollback the transactions.

This sample shows how, based on the exception type, a message can be either retried, sent to the error queue, or ignored. Beware of swallowing exceptions though, since it is almost never intended and the message will be removed from the queue, as if it has been processed successfully.

public void SerializationFailedForMessage(TransportMessage message, Exception e)
{
    SendToErrorQueue(message);
}

public void ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e)
{
    if (e is MyCustomException)
    {
        // Ignore the exception, avoid doing this in a production code base
        Log.WarnFormat("MyCustomException was thrown. Ignoring the error for message Id {0}.", message.Id);
    }
    else
    {
        // Check if enough performed retries, ultimately send to error queue
        SendToErrorQueue(message);
    }
}

To register the new exception handler:

busConfiguration.RegisterComponents(
    registration: configureComponents =>
    {
        configureComponents.ConfigureComponent<CustomFaultManager>(DependencyLifecycle.InstancePerCall);
    });

Related Articles


Last modified