In WebAPI 2 global exception handler, I am trying to get the reference of the controller object from where the error is thrown.
below is the code for it:
public class CustomExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var controller = context.ExceptionContext.ControllerContext;
var action = context.ExceptionContext.ActionContext;
//.....some code after this
}
}
controller
and action
variables above are coming out to be null.
Any pointers why so?
To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration. Configuration. Filters collection. Exception filters in this collection apply to any Web API controller action.
Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.
Assuming that the exception gets thrown from within an action method.
Make sure to return true
from the ShouldHandle
method of your ExceptionHandler
.
Without this, the context.ExceptionContext.ControllerContext
in the Handle
method will be null.
For some reason the context.ExceptionContext.ActionContext
is always null,
but this one can be retrieved from the HttpControllerContext
via its Controller
property.
class MyExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
HttpControllerContext controllerContext = context.ExceptionContext.ControllerContext;
if (controllerContext != null)
{
System.Web.Http.ApiController apiController = controllerContext.Controller as ApiController;
if (apiController != null)
{
HttpActionContext actionContext = apiController.ActionContext;
// ...
}
}
// ...
base.Handle(context);
}
public override Boolean ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
}
If you only care about exception logging, prefer an ExceptionLogger
over an ExceptionHandler
.
See MSDN.
Exception loggers are the solution to seeing all unhandled exception caught by Web API.
Exception loggers always get called, even if we're about to abort the connection.
Exception handlers only get called when we're still able to choose which response message to send.
Here also, retrieve the HttpActionContext
from the HttpControllerContext
as shown above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With