Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Error Handling in ASP.NET Web API 2

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.

like image 810
Greg Gum Avatar asked Jan 07 '23 04:01

Greg Gum


1 Answers

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.

like image 107
Greg Gum Avatar answered Jan 09 '23 18:01

Greg Gum