Monday, 31 December 2018

What is HttpResponseException Web API?

When an exception occurs and it is not handled in Web API code then by default exception is converted to 500, internal server error which is not describing anything about the exception. We have to dig down the code where the exception occurred in the code by debugging. But by using HttpResponseException we can handle the exception in the code and could show a friendly message to the end user like 404, page not found, 500 internal server error, 405 Method Not Allowed, 400 Bad Request etc. Below is the example where we are returning error code 404.

public Employee GetEmployees(int id) { Employee emp = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return emp; }

No comments:

Post a Comment