Logging unhandled exceptions with Nancy

Normally when developing an ASP.NET application I add fall back logging for any unhandled exceptions in Global.asax.cs:

public class Global : HttpApplication
{
    private ILog _logger;
    
    protected void Application_Start(object sender, EventArgs e)
    {
        XmlConfigurator.Configure();
        _logger = LogManager.GetLogger(typeof(Global));
    }

    protected void Application_Error(object sender, EventArgs e)
    {
        var error = Server.GetLastError();
        _logger.Error("Unhandled error", error);
    }
}

This means any YSODs are logged.

When developing applications with Nancy this no longer works, as Nancy has it’s own error handling pipeline.

The solution is to implement a handler to log any unhandled errors:

public class LoggingErrorHandler : IErrorHandler
{
    private readonly ILog _logger = LogManager.GetLogger(typeof(LoggingErrorHandler));

    public bool HandlesStatusCode(HttpStatusCode statusCode)
    {
        return statusCode == HttpStatusCode.InternalServerError;
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        object errorObject;
        context.Items.TryGetValue(NancyEngine.ERROR_EXCEPTION, out errorObject);
        var error = errorObject as Exception;

        _logger.Error("Unhandled error", error);
    }
}

And, as of 0.10.0, there’s no longer any need to register it. Any IErrorHandler implementations will be picked up, auto-magically.

Advertisements

2 thoughts on “Logging unhandled exceptions with Nancy

  1. Johan January 27, 2013 / 6:53 pm

    IErrorHandler has been obsoleted and the way to go now is IStatusCodeHandler

  2. Stoyan May 21, 2015 / 2:23 am

    Thanks for your code. Here it is modified to use the new IStatusCodeHandler

    public class LoggingErrorHandler : IStatusCodeHandler
    {
    private readonly ILog logger = LogManager.GetLogger(typeof(LoggingErrorHandler));

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
    object errorObject;
    context.Items.TryGetValue(NancyEngine.ERROR_EXCEPTION, out errorObject);
    var error = errorObject as Exception;

    logger.Error(“Unhandled error”, error);
    }

    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
    {
    return statusCode == HttpStatusCode.InternalServerError;
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s