Zaid Masud
Zaid Masud

Reputation: 13443

Custom errors on MVC 4 Web API before controller action is invoked

Based on this article I've implemented my own ExceptionFilterAttribute and registered the filter in GlobalConfiguration for custom exception handling in MVC 4 Web API.

However the ExceptionFilterAttribute only gets invoked for exceptions thrown in a controller action, after the request is resolved by the Framework.

I'd like to also implement custom error handling for exceptions thrown before a controller action is called. For example, an exception that is thrown in a DelegatingHandler currently returns me the following HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Exception of type 'System.Exception' was thrown.</title>
        ...

What do I need to do to return my own custom error for this scenario?

Upvotes: 1

Views: 240

Answers (1)

Sixto Saez
Sixto Saez

Reputation: 12680

If the DelegatingHandler exceptions are generated from filters that you've written, then you can add another filter to "trap" some of these exceptions as shown in this SO answer.

As you've found out and is documented in that SO answer, you are very limited in which exceptions you'll actually "trap" from the Web API pipeline. The only option I see to try to do what you're describing is to write a custom HttpMessageHandler as demonstrated in this good article.

Upvotes: 1

Related Questions