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.
IErrorHandler has been obsoleted and the way to go now is IStatusCodeHandler
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;
}
}