Click here to Skip to main content
15,892,005 members
Articles / Web Development / ASP.NET

Exception Handling in ASP.NET Web API

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
27 Jan 2014CPOL2 min read 21.6K   5   2
Exception handling in ASP.NET Web API

In one of my previous articles, we explored how to handle Exceptions in WCF RESTful services. In this article, the focus is the same - to handle exceptions but for ASP.NET Web API service. HttpResponseException class plays its role to return HTTP status code as well as further exception details to client.

We can simply return respective error status code from Web API service instead of a 500 generic error code, i.e., Internal Server Error. Here, we will implement exception handling for the same ASP.NET Web API service created earlier in a tutorial, i.e., "Simply create ASP.NET Web API service with all CRUD operations".

Now, we have Web API service controller StudentController having GET method taking "Id" as parameter and returns a student against it. If student doesn't exist against a provided student Id, then we can handle and throw the exception with respective status code, i.e., "Not Found".

After adding the exception handling code using HttpResponseException class, GET method implementation will be as follows:

C#
public Student Get(string id)
{
Student student =  StudentRepository.GetStudent(id);
if (student == null)
throw new HttpResponseException(HttpStatusCode.NotFound);

return student;
}

It looks nice to return logical status code back to client but what if we wanted to add more error details?

ASP.NET Web API allows us to create response message using HttpResponseMessage class and pass it to HttpResponseException.

HttpResponseMessage represents a returning response message having the following important properties:

  • StatusCode is HTTP response status code, i.e., NotFound in our case
  • ResonPhrase to return the exception reason along with status code
  • Content property can be used to set or get HTTP response content
C#
public Student Get(string id)
{
    Student student = StudentRepository.GetStudent(id);
    if (student == null)
    {
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            responseMessage.StatusCode = HttpStatusCode.NotFound;
            responseMessage.ReasonPhrase = "Student not found";
            responseMessage.Content = new StringContent("No student exists against provided student id");

            throw new HttpResponseException(responseMessage);
     }
      return student;
}

Note: Remember one important thing about HttpResponseMessage class. Initially, we can easily create a type and pass it to HttpResponseMessage class constructor and return that message with data. But now, we can only use Content property to set message content.

Hopefully, this web application development tutorial will be helpful in order to understand and implement exception handling in ASP.NET Web API services.

More Related Articles

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

Comments and Discussions

 
QuestionHow do we add an object to the Content Pin
Member 106769542-May-14 0:15
Member 106769542-May-14 0:15 
GeneralMy vote of 3 Pin
Member 1054729328-Jan-14 7:24
Member 1054729328-Jan-14 7:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.