How to handle errors in ASP.NET Web API

Learn to handle runtime errors using exceptions and return appropriate error codes and error messages in ASP.NET Web API

How to handle errors in ASP.NET Web API
RapidEye / Getty

Microsoft’s ASP.NET Web API is a lightweight framework you can use to build stateless RESTful services that run on HTTP. Exceptions are errors that occur at runtime, and exception handling is the technique of handling runtime errors in your application code.

Every ASP.NET Web API developer should know how to handle exceptions in Web API and how to send out appropriate error codes and error messages from Web API controller methods. We will examine how to perform these tasks in the sections below. 

Using HttpResponseException in ASP.NET Web API

You can use the HttpResponseException class to return specific HTTP status codes and messages from your controller methods in Web API. Here is an example.

public Employee GetEmployee(int id)
{
    Employee emp = employeeRepository.Get(id);
    if (emp == null)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent("Employee doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
            StatusCode = HttpStatusCode.NotFound
        }
        throw new HttpResponseException(response);
    }
    return emp;
}

To continue reading this article register now

How to choose a low-code development platform