How to handle the exception in Asp.net 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 asp.net 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 asp.net 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);
            }
            else
            {
                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

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.