How to handle the exception in Web API ? (Part 5)

Exception handling is the one of the good approach to find out the exact error in the application at run time.
In web API there are so many approaches to handle the exception in code like

1. Using HttpResponseException
2. Using HttpError
3. Using Exception Filters
4. Using Exception Handlers

Now we will see how to use the HttpResponseException in web API action Method

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

public IHttpActionResult GetEmpDetail(int id)
            tblEmp objEmp = db.tblEmps.Find(id);
            if (objEmp == null)
                  throw new HttpResponseException(HttpStatusCode.NotFound);
                return Ok(objEmp);

But this above method will not give the more specific error message, so if we have to get the user friendly error message we can write the code like this

If we will run the application and test on postman, then we will get the output like this


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.