2

I know there are plenty of threads about this topic but none provides an entire and full working solution.

Scenario

I have an application which is providing both, MVC 5 and Web Api 2.2 controllers. I have the need of catching all exceptions (including 404, 401) and return always a custom JSON error structure.

Partial Solution

So far I have implemented, a custom ExceptionFilterAttribute as following:

public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.Response = context.Request.CreateResponse(
            HttpStatusCode.InternalServerError,
            new
            {
                Title = "An Error occured while processing the request",
                Message = context.Exception.ToString(),
                Type = "Error",
                Code = context.Exception.HResult
            });
        context.Response.ReasonPhrase = "An Error occurred while processing the request";
    }
}

Then I also extended and replaced the available ExceptionHandler service as following:

public class GenericExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = HttpResponseFactory.BadResponse(
            context.Request,
            "An unhandled error occurred",
            context.Exception.Message,
            10000);
    }   
}

And I swap both during my initialization:

public static void Register(HttpConfiguration config)
{
    // authentication
    config.Filters.Add(new AuthorizeAttribute());
    // error handler
    config.Filters.Add(new ExceptionFilter());
    // error service
    config.Services.Replace(typeof(IExceptionHandler), new GenericExceptionHandler());
}

Unfortunately when I generate:

  1. 401 - Not Authorized
  2. 404 - Not Found
  3. certain 500 - Internal Server Error

I cannot catch the exception. Is there any way to achieve it?

8
  • when I generate... Where? How? Commented Jan 17, 2017 at 13:02
  • have you tried to implement the IExceptionLogger ? Commented Jan 17, 2017 at 13:03
  • @PatrickHofman I just send an non-authenticated request, I get back 401 but I can't intercept the response generated by ASP.NET stack Commented Jan 17, 2017 at 13:10
  • 1
    I am not debating. I am trying to get enough information to write up an answer, if that is what you'd like me to do... :) Commented Jan 18, 2017 at 9:38
  • 2
    How is this a duplicate of that question when the OP is not even using global.asax? Commented Jan 19, 2017 at 3:48

1 Answer 1

2

Put this in your Global file:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();

    // Do something with the error.
    System.Diagnostics.Debug.WriteLine(exception);

    // Redirect somewhere or return an error code in case of web api
    Response.Redirect("/Home/Error");
}

Anytime, an error occurs, ASP MVC will call that method.

Sign up to request clarification or add additional context in comments.

3 Comments

I am using OWIN, I don't have Global.asax
So add one. I do not think using OWIN means no Global.asax file.
For some reason this only catches some errors... e.g. if I navigate to a non-existent page, then Application_Error fires, but if an exception is thrown from the code then it doesn't..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.