I know there are plenty of threads about this topic but none provides an entire and full working solution.
Scenario
I have an application which is providing both, MVC 5 and Web Api 2.2 controllers. I have the need of catching all exceptions (including 404, 401) and return always a custom JSON error structure.
Partial Solution
So far I have implemented, a custom ExceptionFilterAttribute as following:
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
context.Response = context.Request.CreateResponse(
HttpStatusCode.InternalServerError,
new
{
Title = "An Error occured while processing the request",
Message = context.Exception.ToString(),
Type = "Error",
Code = context.Exception.HResult
});
context.Response.ReasonPhrase = "An Error occurred while processing the request";
}
}
Then I also extended and replaced the available ExceptionHandler service as following:
public class GenericExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = HttpResponseFactory.BadResponse(
context.Request,
"An unhandled error occurred",
context.Exception.Message,
10000);
}
}
And I swap both during my initialization:
public static void Register(HttpConfiguration config)
{
// authentication
config.Filters.Add(new AuthorizeAttribute());
// error handler
config.Filters.Add(new ExceptionFilter());
// error service
config.Services.Replace(typeof(IExceptionHandler), new GenericExceptionHandler());
}
Unfortunately when I generate:
- 401 - Not Authorized
- 404 - Not Found
- certain 500 - Internal Server Error
I cannot catch the exception. Is there any way to achieve it?
IExceptionLogger?