Does the custom class HandleErrorAttribute not use exceptions?

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)
    {
        // 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)
        };
    }
} 

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.");
    }
}
+4
source share
2 answers

ApiController does not match the MVC controller, and therefore it probably will not work. Error handling is handled differently in the Web API. Check the following link for exception handling attributes for the web API:

http://www.asp.net/web-api/overview/error-handling/exception-handling

+2

:

 filters.Add(new HandleControllerErrors {View = "Error"});
0

Source: https://habr.com/ru/post/1598268/


All Articles