Error notifications

Component: NServiceBus
NuGet Package NServiceBus (6.x)

Error notifications are available for several events.

The following example shows how to be notified every time a message is handled by recoverability. While this code writes to the console any other action could be taken, for example sending an email or writing to a monitoring system.

void EndpointStartup()
{
    var endpointConfiguration = new EndpointConfiguration("EndpointName");
    Subscribe(endpointConfiguration.Notifications);
}

void Subscribe(Notifications notifications)
{
    var errors = notifications.Errors;
    errors.MessageHasBeenSentToDelayedRetries += LogEvent;
    errors.MessageHasFailedAnImmediateRetryAttempt += LogEvent;
    errors.MessageSentToErrorQueue += LogEvent;
}

static string GetMessageString(byte[] body)
{
    return Encoding.UTF8.GetString(body);
}

void LogEvent(object sender, FailedMessage failed)
{
    log.Fatal($@"Message sent to error queue.
Body:
{GetMessageString(failed.Body)}");
}

void LogEvent(object sender, DelayedRetryMessage retry)
{
    log.Info($@"Message sent to Delayed Retries.
RetryAttempt:{retry.RetryAttempt}
Body:
{GetMessageString(retry.Body)}");
}

void LogEvent(object sender, ImmediateRetryMessage retry)
{
    log.Info($@"Message sent to Immedediate Retry.
RetryAttempt:{retry.RetryAttempt}
Body:
{GetMessageString(retry.Body)}");
}

Performance Impact

Notifications are executed on the same thread as the NServiceBus pipeline. If long running work needs to be done it should be executed on another thread otherwise the message processing performance can be impacted.

The notification instance is also injected into the container.

Unsubscribing

Since notifications are global for the current endpoint it is also important to ensure no longer required subscriptions removed so as to not unnecessarily impact performance.

This is done by detaching from the event.

Message Body

Since the message could have failed due to a de-serialization exception it is not possible for the API to provide the instance of the message. For the same reason is it recommended that consumers of this API do not attempt to deserialize the message instance. If the message contents is required for debugging purposes it is recommended to convert it to a string using the .net encoding APIs.

Samples


Last modified