Exception Handling in ASP.NET Web API
by Mike Wasson
This article describes error and exception handling in ASP.NET Web API.
What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.
The HttpResponseException type is a special case. This exception returns any HTTP status code that you specify in the exception constructor. For example, the following method returns 404, Not Found, if the id parameter is not valid.
[!code-csharpMain]
1: public Product GetProduct(int id)
2: {
3: Product item = repository.Get(id);
4: if (item == null)
5: {
6: throw new HttpResponseException(HttpStatusCode.NotFound);
7: }
8: return item;
9: }
For more control over the response, you can also construct the entire response message and include it with the HttpResponseException:
[!code-csharpMain]
1: public Product GetProduct(int id)
2: {
3: Product item = repository.Get(id);
4: if (item == null)
5: {
6: var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
7: {
8: Content = new StringContent(string.Format("No product with ID = {0}", id)),
9: ReasonPhrase = "Product ID Not Found"
10: }
11: throw new HttpResponseException(resp);
12: }
13: return item;
14: }
You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.
[!NOTE] Exception filters in ASP.NET Web API are similar to those in ASP.NET MVC. However, they are declared in a separate namespace and function separately. In particular, the HandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.
Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
[!code-csharpMain]
1: namespace ProductStore.Filters
2: {
3: using System;
4: using System.Net;
5: using System.Net.Http;
6: using System.Web.Http.Filters;
7:
8: public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
9: {
10: public override void OnException(HttpActionExecutedContext context)
11: {
12: if (context.Exception is NotImplementedException)
13: {
14: context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
15: }
16: }
17: }
18: }
The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client.
## Registering Exception Filters
There are several ways to register a Web API exception filter:
- By action
- By controller
- Globally
To apply the filter to a specific action, add the filter as an attribute to the action:
[!code-csharpMain]
1: public class ProductsController : ApiController
2: {
3: [NotImplExceptionFilter]
4: public Contact GetContact(int id)
5: {
6: throw new NotImplementedException("This method is not implemented");
7: }
8: }
To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:
[!code-csharpMain]
1: [NotImplExceptionFilter]
2: public class ProductsController : ApiController
3: {
4: // ...
5: }
To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.
[!code-csharpMain]
1: GlobalConfiguration.Configuration.Filters.Add(
2: new ProductStore.NotImplExceptionFilterAttribute());
If you use the ???ASP.NET MVC 4 Web Application??? project template to create your project, put your Web API configuration code inside the WebApiConfig
class, which is located in the App_Start folder:
[!code-csharpMain]
1: public static class WebApiConfig
2: {
3: public static void Register(HttpConfiguration config)
4: {
5: config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());
6:
7: // Other configuration code...
8: }
9: }
The HttpError object provides a consistent way to return error information in the response body. The following example shows how to return HTTP status code 404 (Not Found) with an HttpError in the response body.
[!code-csharpMain]
1: public HttpResponseMessage GetProduct(int id)
2: {
3: Product item = repository.Get(id);
4: if (item == null)
5: {
6: var message = string.Format("Product with id = {0} not found", id);
7: return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
8: }
9: else
10: {
11: return Request.CreateResponse(HttpStatusCode.OK, item);
12: }
13: }
CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally, CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessage that contains the HttpError.
In this example, if the method is successful, it returns the product in the HTTP response. But if the requested product is not found, the HTTP response contains an HttpError in the request body. The response might look like the following:
[!code-consoleMain]
1: HTTP/1.1 404 Not Found
2: Content-Type: application/json; charset=utf-8
3: Date: Thu, 09 Aug 2012 23:27:18 GMT
4: Content-Length: 51
5:
6: {
7: "Message": "Product with id = 12 not found"
8: }
Notice that the HttpError was serialized to JSON in this example. One advantage of using HttpError is that it goes through the same content-negotiation and serialization process as any other strongly-typed model.
HttpError and Model Validation
For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:
[!code-csharpMain]
1: public HttpResponseMessage PostProduct(Product item)
2: {
3: if (!ModelState.IsValid)
4: {
5: return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
6: }
7:
8: // Implementation not shown...
9: }
This example might return the following response:
[!code-consoleMain]
1: HTTP/1.1 400 Bad Request
2: Content-Type: application/json; charset=utf-8
3: Content-Length: 320
4:
5: {
6: "Message": "The request is invalid.",
7: "ModelState": {
8: "item": [
9: "Required property 'Name' not found in JSON. Path '', line 1, position 14."
10: ],
11: "item.Name": [
12: "The Name field is required."
13: ],
14: "item.Price": [
15: "The field Price must be between 0 and 999."
16: ]
17: }
18: }
For more information about model validation, see Model Validation in ASP.NET Web API.
Using HttpError with HttpResponseException
The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseException to return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error:
[!code-csharpMain]
1: public Product GetProduct(int id)
2: {
3: Product item = repository.Get(id);
4: if (item == null)
5: {
6: var message = string.Format("Product with id = {0} not found", id);
7: throw new HttpResponseException(
8: Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
9: }
10: else
11: {
12: return item;
13: }
14: }
|