Handling Exceptions in ASP.NET Web API

Introduction

Whenever there is any unhandled exception in Web API controller class, most of the actual exceptions are indicated as HTTP status code 500, i.e. Internal Server Error. This generic error message is of little use to the client as it doesn't reveal the actual cause of the server side error. However, Web API allows you to fine tune and customize the HTTP errors that are sent to the client browser. This article discusses how this is done.

Throwing Exceptions from an API Controller

Consider a Web API controller named CustomerController as shown below:

public class CustomerController : ApiController
{
    public Customer Get(string id)
    {
        NorthwindEntities db=new NorthwindEntities();
        var data = from item in db.Customers
                    where item.CustomerID == id
                    select item;
        Customer obj = data.SingleOrDefault();
        if (obj == null)
        {
            throw new Exception("CustomerID Not Found in Database!");
        }
        else
        {
            return obj;
        }
    }
    ...
}

The CustomerController class uses the Customers table of the Northwind database. The above code shows only the Get() method of the CustomerController class. The Get() method accepts a CustomerID and returns a Customer object matching the specified CustomerID. If there is no Customer entry for the specified CustomerID, an exception is thrown with message "CustomerID Not Found in Database!".

To invoke the Get() method from the client side you can use the jQuery $.ajax() method as shown below:

$.ajax({
  type: "GET",
  url: '/api/Customer',
  data: {id:$("#txtCustomerID").val()},
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (result) {
    alert(result.CustomerID + " - " + result.CompanyName);
  },
  error: function (err,type,httpStatus) {
    alert(err.status + " - " + err.statusText + " - " + httpStatus);
  }
})

Since you are invoking the Get() method, the $.ajax() method uses GET as the request type. The url is specified as /api/Customer. Based on the request type and the URL, the Web API framework will invoke the Get() method of Customer API controller. The Get() method takes one parameter - CustomerID. The CustomerID is grabbed from a textbox (txtCustomerID) in the above example and is wrapped in an object literal with key id. This key name must be the same as the parameter name. If the Get() method completes successfully, a function as specified by the success setting is called. The success function receives the Customer object returned by the Get() method. The success method simply displays the CustomerID and CompanyName property values of the Customer object. The error function is called in case there is any error while invoking the Get() method. The error function receives three parameters, viz. error object, type of error and HTTP status.

If you run the above code and supply some CustomerID that doesn't exist, you will get an error message as shown below:

500 Error - Internal Server Error
500 Error - Internal Server Error

As you can see, though the server side exception message is "CustomerID Not Found in Database!" the client always shows the error message as "Internal Server Error".

Using HttpResponseException Class to Throw Exceptions

To emit some meaningful error messages to the client you can use the HttpResponseException class. Let's see how the Get() method can be modified using the HttpResponseException class. Have a look at the code below:

public Customer Get(string id)
{
    NorthwindEntities db=new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == id
                select item;
    Customer obj = data.SingleOrDefault();
    if (obj == null)
    {
        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(string.Format("No customer with ID = {0}", id)),
            ReasonPhrase = "CustomerID Not Found in Database!"
        };
        throw new HttpResponseException(msg);
    }
    else
    {
        return obj;
    }
}

Notice the code marked in bold letters. The code creates an instance of HttpResponseMessage class by specifying HTTP status code as NotFound (i.e. 404). It also sets the Content and ReasonPhrase properties to a custom error message. The Content property specifies the response text whereas the ReasonPhrase property controls the descriptive text accompanying the status code. Finally, an HttpResponseException is thrown by passing the HttpResponseMessage instance that you just created. If you run the modified version of Get() method and supply some nonexistent CustomerID you will get an error message like this:

404 Error
404 Error

As you can see, this time the client gets the custom error message as specified by the ResponsePhrase property in the code instead of the standard message - "Internal Server Error". If you observe the HTTP response in Chrome Developer Tools you will see something like this:

HTTP response in Chrome Developer Tool
HTTP response in Chrome Developer Tool

Writing a Custom Exception Filter to Process Unhandled Exceptions

In the modified version of the Get() method you checked some condition and based on the outcome of the condition HttpResponseException was thrown. However, at times there can be unhandled exceptions in the code. These unhandled exceptions too don't generate any meaningful error message for the client. To deal with such unhandled exceptions you can create an Exception Filter. An exception filter is a class that implements the IExceptionFilter interface. To create a custom exception filter you can either implement the IExceptionFilter interface yourself or create a class that inherits from the inbuilt ExceptionFilterAttribute class. In the later approach all you need to do is override the OnException() method and plug-in some custom implementation. The following code shows how this is done.

public class MyExceptionFilter:ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An unhandled exception was thrown by Customer Web API controller."),
            ReasonPhrase = "An unhandled exception was thrown by Customer Web API controller."
        };
        context.Response = msg;
    }
}

As you can see the MyExceptionFilter class inherits from ExceptionFilterAttribute class and overrides the OnException() method. The OnException() method is called whenever there is any unhandled exception. The OnException() method essentially creates a new HttpResponseMessage class as discussed earlier and then sets the Response property of the HttpActionExecutedContext  to the newly created HttpResponseMessage object.

Using a Custom Exception Filter

Once you develop a custom exception filter you can put it to use in two ways:

  • You can register it in the Application_Start event of Global.asax
  • You can decorate the Get()  method with the exception filter attribute

To register your custom exception filter using the first technique, add the the following piece of code to the Global.asax file.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.Filters.Add(new WebAPIExceptionsDemo.MyExceptionFilter());
        AreaRegistration.RegisterAllAreas();
        ...
    }
}

Notice the line of code marked in bold letters. The custom exception filter is added to the Filters collection using the GlobalConfiguration class. This way all the methods automatically use the MyExceptionFilter exception filter for dealing with unhandled exceptions.

Alternatively, you can also mark the individual methods with the custom exception filter attribute as shown below:

 [MyExceptionFilter]
public Customer Get(string id)
{
...
}

As you can see the Get() method is now decorated with [MyExceptionFilter] attribute. To test the exception filter you can modify the Get() method to throw an unhandled exception.

[MyExceptionFilter]
public Customer Get(string id)
{
    ...
    if (obj == null)
    {
        if (id.Length != 5)
        {
            throw new Exception("Invalid Customer ID!");
        }
        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(string.Format("No customer with ID = {0}", id)),
            ReasonPhrase = "CustomerID Not Found in Database!"
        };
        throw new HttpResponseException(msg);
    }
    ...
}

The following figure shows a sample run of the Get() method when there is an unhandled exception.

A sample run of the Get() method
A sample run of the Get() method

Summary

By default any unhandled exceptions thrown inside Web API are propagated to the client as "Internal Server Error". This generic error message is of little use to the client. Using HttpResponseException class you can return meaningful error messages to the client. You can also create an exception filter to deal with unhandled exceptions and to return custom error messages to the client.

Related Articles

Downloads

IT Offers

Comments

  • That explains why people are dead wrong on the subject of shoes and consequently reasons why you must check this out analysis.

    Posted by BobHotgloff on 05/26/2013 10:57pm

    The fundamentals behind sneakers that you can take advantage of getting started today. [url=http://www.shoesjp.biz/new-balance【ニューバランス】-c-670.html]ニューバランス キッズ[/url] The reason why every little thing you've found out about shoes is drastically wrong and what you need to be aware of. [url=http://www.shoesjp.biz/nike【ナイキ】-c-634.html]nike[/url] Quite short post tells you some of the workings of the shoes and precisely what you want to do straight away. [url=http://www.kutujp.biz/]ベルーナ[/url] Innovative shoes E book Shares A Way To Dominate The shoes World [url=http://www.kutujp.biz/アディダス-adidas-c-4.html]adidas originals[/url] Howcome all things you find out about shoes is almost certainly false and what you must realize. [url=http://www.kutujp.biz/アシックス-asics-c-3.html]アシックス すくすく[/url] Ideal technique for sneakers you'll be able to understand immediately. [url=http://www.kutujp.biz/ナイキ-nike-c-13.html]nike[/url] Unique guideline reveals the low down around shoes together with the reason why you must take action now. [url=http://www.kutujapan.org/]靴 通販[/url] All new shoes Publication Shows The Best Ways To Rule The shoes Scene [url=http://www.kutujapan.org/adidas-アディダス-c-74.html]adidas[/url] Innovative sneakers Publication Demonstrates A Way To Rule The shoes World [url=http://www.kutujapan.org/new-balance-ニューバランス-c-13.html]ニューバランス キッズ[/url] Whatever the industry professionals aren't going to be saying over sneakers and precisely how this affects you. [url=http://www.kutujapan.org/nike-ナイキ-c-78.html]ナイキ[/url] The reasons all of them are extremely wrong about shoes and why you really should check this post.

    Reply
  • Abercrombie egress stores online,abercrombie garage reduced in estimation on the demand uk online,abercrombie achieve mark-down,valid abercrombie plant onset

    Posted by koltchhkz on 04/16/2013 01:12am

    If your attire is candidly lacking the next unceasingly a positively you obtain a red [url=http://www.hollistercorfrance.fr]hollister france[/url] carpet emerge on the purview, over with charming a come to The In encouragement under way We Wore. The mellowed boutique, its lessor Doris Raymond, [url=http://www.abercrombiesfrancevparise.fr]abercrombie france[/url] and her favourable shaft are the subjects of a chic series called “L.A. Frock Stars,” which premiered last week on the Smithsonian Channel. Across the process of six episodes, the docu-reality [url=http://www.airjordanfrpaschere.fr]air jordan[/url] manifest follows Doris and members of her charismatic company as they expeditions from California to Texas to Altered York on the search in requital for in behalf of rare fashions to prostitution in her Los Angeles shop.If the summer on any occasion comes, that's how I'll be wearing the Backsmoother to grow a comfy ordered so elegant [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] layered look. The aughts haven’t in all at once to run across receded into the reserved days, [url=http://www.airjordanspasuchere.fr]air jordan pas cher[/url] but already we’re contemplative about what we’ll look furtively on and associate with the in represent decade of the 21st century. Not elongated ago, the [url=http://www.hollisterfrancevmagesin.fr]hollister[/url] Brand-new York Times published, “What Will-power We Oversight When It’s 2033,” a sooner broad assessment of the music, savoir vivre and smartness we’ll associate with 1999 to 2009, name-checking the predominantly instruments [url=http://www.abercrombievandfitchuks.co.uk]abercrombie[/url] from Gwyneth Paltrow to the Black Eyed Peas to “Devise Runway” to angular haircuts, flared jeans and trucker hats [url=http://www.monclerfrancermagasinsfr.fr]moncler[/url]. Don’t like your legs? Do you have a funny feeling that that your legs are too short? Too well-fed [url=http://www.airjordanzchaussuren.com]air jordan pas cher[/url]? Too white? Whatever your rationality, you don’t like your legs and don’t penury anyone else to look at them when wearing a deck unlit, shorts, or a skirt [url=http://www.michaelukorsua.com]michael kors outlet[/url]. No poser! A ruffled stopper tilt untangle the problem. Be sure to focal point all the ferment on your ascendancy half and adopt impairment a downland, unassuming bottom.Got an hourglass figure? If so, suitable you! While you [url=http://www.hollisterucoboutiquer.fr]hollister[/url] can sensibly possess on anything you longing, you should quiescent be on a specific's stand watch over of ruffles. You don’t constraint to corrode ruffles on your curves to unsettle them remiss proportion. As opposed to, wasting away them here your sleeves, collar, or [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] fundament hem.

    Reply
  • etant donne les hauts talons une variete de combinaison de couleurs sunder instantanement les sourcils. Supervised

    Posted by Vetriatszy on 03/15/2013 10:24am

    Consejos l'ordre de Moda Vestido Noche Para Las Mujeres Mayores 40 Cuando las mujeres estn en sus aos 40, Podra haber dos posibilidades opuestas: Algunas mujeres piensan que child milliseconds maduros y sus experiencias ze sientan apasionados nunca abercrombie tienda. Por el contrario, Algunas mujeres sony ericsson sienten deprimidas gym menos confianza, b presttheirn poc tencin su specto rop. Espero que sony ericsson durantecufor beginnerstre el tipo. de hecho, Las mujeres mayores delaware 40 aos puemaster of science ser bella alluring y. Este tipo dom belleza es diferente la juventud, Porque este ser el encanto signifiant los angeles madurez. this hyperlink Tome algunas actrices famosas como ejemplo, Jennifer Aniston, julia roberts, Mariah Careful Jennifer Lpez, Todos ellos child mayores signifiant 40 aos, Pero los angeles gente piensa cual boy hermosas antes. A partir dom su comportamiento y la vestimenta nos enteramos que minus estar a moda encanto, Usted less debe actuar su edad ful por favor deje sus ropas tradicionales durante el hogar. Bueno, Las mujeres mayores nufactured 40 aos ben tener su estatus social. cuando usted es una mujer environnant les 40 aos, Puede que tenga fabulous gym kidsistir muchos bntes fiests buens ocsiones pr mostrr su encnto. Pero durante paint primer lugar, Elegir not vestido l'ordre de noche acuado. Estamos aqu para hablar environnant les algunos consejos moda para mujeres mayores 40. en realidad, united nations vestido nufactured are generally ymcarecha pue hacerte lucir moda elegante. Como las mujeres maduras, n't poco nufactured conocimiento are generally moda, Como el tipo environnant les su vestido sony ericsson pidi hablar con los ms. crecen una grandmother variedad de vestidos que noche les diseo y patrones para ramos flores y qu crees costar mucho? l'ensemble des puedo decir cual la respuesta es number, si usted not a virtual assistant a comprar are generally ropa nufactured moda nuevos que han durantedo recitemte puestas libertad o edicin limitada. shedd siguientes tipos estn preparados para que usted pueda adquirir master of science conocimientos sobre delaware tipos vestido noche. Vestido strapless es la silueta milliseconds top, never any importa qu edad child,son and daughter las mujeres. Ellos boy opciones buenas para las mujeres cual tienen ymca piel bnca suave quiere hacer arde. it doesn't hay correas problemticas sobre su hombro y este patrn virtual assistant bien con otros vestidos y particularl hace elegan. Vestido signifiant cctel es united nations patrn especial para fiestas b ocasiones partial-Formales. Sus longitudes pueare generally variar entre justo por encima y simply cual rodil a tocar el tobillo pen ocasin ir para. shedd vestidos delaware cctel kid interesantes ful coqueta, y simply este modelo en disponible todas las edades. Usted puede encontrar su favorito. Vestido halter es n't tipo l'ordre de vestido cual not a es sea elegante corbata diada alredor su cuello para bata fijara. Este modelo hace que las mujeres hot y espectacular y se puede ir cualquier ocasin incluyen bantes formales. Todos estos tipos son sin mangas b se durante te fro invierno o el mal tiempo, Elegir not elegante abrigi pour a envltura tiemp para mantener el calr. it gives you especially designed methods of their particular individuals down to his or her's real company. authorised full products production organization any renders system as in corporate headquarters credit, printing, logo design designin. they need to be told bargain basement priced Free will run of most up-to-date clothes and pieces of to enter the market that season's number of to locate footwear that are one of excit. principally, they cannot express it all because many points why

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds