6

Preamble: This question is different from "Exception Handling in ASP.net Web API" as the OP was looking for custom Error Handling, not global handling. It also differs from other earlier questions that were answered, as those were for earlier versions of Web API, not version 2. Also note I am going to self answer this question. It took quite some searching to find the correct answer.

The question is: How do I globally handle errors in Web API 2.0? The error handling I have set up for MVC does not get activated for web api calls and I need to generically handle any error that is thrown so that relevant error information is returned to the client.

1 Answer 1

11

Global Error handling is correctly answered in this asp.net article. However the articles is missing a few important points to make the code actually work.

The article covers the details, but here it is in a nutshell:

  1. Global Error Handling is already included in System.Web.Http.ExceptionHandling The classes in the article are already in this library, so there is no need to rewrite them.

  2. The only class you need to write is the one which is customized for your app. In the article, they call it the "OopsExceptionHandler" However, the one written in the article does not compile. This is the updated code that does work:

    public class OopsExceptionHandler : ExceptionHandler
    {
       public override void  Handle(ExceptionHandlerContext context)
       {
        context.Result = new TextPlainErrorResult
        {
            //If you want to return the actual error message
            //Content = context.Exception.Message 
            Request = context.ExceptionContext.Request,
            Content = "Oops! Sorry! Something went wrong." +
                      "Please contact [email protected] so we can try to fix it."
        };
    }
    
    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }
    
        public string Content { get; set; }
    
        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response =
                             new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent(Content);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
    } 
    
  3. You then need to register the ExceptionHandler. An example of this is not given in the article, so here it is:

    config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());
    

This line goes in the WebApiConfig file, in the register method. Note that it is using 'Replace' not 'Add' as it will error out on Add. Only one is allowed by the framework.

That is all that is required. To test, throw an error from your web API and you will see the error message returned as the content of the webAPI call. Note that there are security implications to returning error messages to the client, so make sure this is what you really want.

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

2 Comments

This is probably the most user friendly answer I've seen on StackOverflow. So often people leave out the small details that would take hours to figure out otherwise. This looks relatively easy, but contradicts the first line of the article: 'Today there's no easy way in Web API to log or handle errors globally'. Perhaps that was just describing a problem that is now resolved because of this article. So, in your opinion @Greg0, is global error handling in Web API 2 readily possible and relatively simple?
@KyleVassella, Yes it is readily possible and relatively simple. With the article, and the summary above, it is quite straightforward. However, having said that, aspnetcore makes it even easier, so if you are just getting started, I definitely recommend that route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.