Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HandleErrorAttribute derived class is not catching exceptions?

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.");
    }
}
like image 774
Robert Oschler Avatar asked Oct 19 '22 07:10

Robert Oschler


1 Answers

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

like image 78
moarboilerplate Avatar answered Oct 31 '22 15:10

moarboilerplate