I have a ASP.NET MVC web app and I am trying to improve its error handling capabilities. I read up on the HandleErrorAttribute base class and wanted to use that with my controller classes. However, when I throw a test Exception from a method in one of my controller classes that is decorated with that attribute, the OnException override in my derived class is not triggered. Instead of my derived error handling class's OnException method being triggered, I see a generic error message in XML format and the generic error message is not found anywhere in my app:
<Error>
<Message>An error has occurred.</Message>
</Error>
What am I doing wrong?
Note I tried adding the following custom errors element to the system.web element in my web.config file as indicated by this SO post, but it didn't help:
ASP.net MVC [HandleError] not catching exceptions
<customErrors mode="On" defaultRedirect="Error" />
Here is my HandleErrorAttribute derived class:
public class HandleControllerErrors : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
// Breakpoint set here never hit.
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");
filterContext.Result = new ViewResult()
{
// Use the ErrorInController view.
ViewName = "ErrorInController",
ViewData = new ViewDataDictionary(model)
};
}
}
Here is how I decorate my controller class. I have a method in it that forcibly throws an exception that is not inside a try/catch block.:
[HandleControllerErrors]
public class ValuesController : ApiController
{
[Route("Api/TestException/")]
public IHttpActionResult TestException()
{
throw new InvalidCastException("Fake invalid cast exception.");
}
}
An ApiController is not the same as an MVC Controller, and as such this will probably not work. Error handling is handled a bit differently in Web API. Check the following link for exception handling attributes for Web API:
http://www.asp.net/web-api/overview/error-handling/exception-handling
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