Friday, December 12, 2014

NancyFX global error handling

Add global error handling to NancyFX Web API is very easy. We need to add a Bottstapper class and inherit it from DefaultNancyBootstrapper. Let's override RequestStartup method.


public class Bootstrapper : DefaultNancyBootstrapper
{
    private ILogger logger;

    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        pipelines.OnError += (ctx, e) =>
        {
            this.logger.Error(e.Message, e);

            return null;
        };

        base.RequestStartup(container, pipelines, context);
    }
}

This method is executed on each call, if any unhandled exception happens we will end up here.