Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application_Error isn't triggered in asp.net web api

How do I get the Application_Error triggered in an ASP.NET WebAPI application? The error I'm having now is that when we resolve a controller through NInject and fails it won't got into Application_Error and we can't log the error since we are doing the global logging in Application_Error.

We also have a global filter for handling error, but that is only triggered if we have found a controller but since we are failing we instantiating the controller we won't go through any filters.

So how do I catch an Exception raised why trying to create the controller handling the response?

like image 947
Tomas Jansson Avatar asked Jun 06 '13 10:06

Tomas Jansson


1 Answers

ASP.Net Web API has its own Exception Handler, you can override it and re-throw exception from there in order to handle it in Application_Error

public class MyExceptionHandler : IExceptionHandler
{
    public virtual Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        ExceptionDispatchInfo.Capture(context.Exception).Throw();
        return Task.CompletedTask;
    }
}

you also need to add MyExceptionHandler class to Web API services.

httpConfiguration.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());
like image 142
Kahbazi Avatar answered Oct 03 '22 05:10

Kahbazi