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