I have an ASP.NET MVC web application and am trying to improve its error handling capabilities. I read the base class HandleErrorAttribute and wanted to use it with my controller classes. However, when I throw a test exception from a method in one of my controller classes that is decorated with this attribute, an OnException override in my derived class does not fire . Instead of triggering the OnException method of the error handler, I see a general error message in XML format, and a general error message is not found anywhere in my application:
<Error>
<Message>An error has occurred.</Message>
</Error>
What am I doing wrong?
Note. I tried adding the following custom error element to the system.web element in the web.config file , as indicated by this SO post, but this did not help:
ASP.net MVC [HandleError] does not use exceptions
<customErrors mode="On" defaultRedirect="Error" />
Here is my derived class HandleErrorAttribute:
public class HandleControllerErrors : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");
filterContext.Result = new ViewResult()
{
ViewName = "ErrorInController",
ViewData = new ViewDataDictionary(model)
};
}
}
This is how I decorate my controller class. I have a method that forces an exception that is not inside the try / catch block .:
[HandleControllerErrors]
public class ValuesController : ApiController
{
[Route("Api/TestException/")]
public IHttpActionResult TestException()
{
throw new InvalidCastException("Fake invalid cast exception.");
}
}
source
share