[ASP. NET Web API tutorial] 4.3 Exception Handling and API Exception Handling in ASP. NET Web APIs

Source: Internet
Author: User

[ASP. NET Web API tutorial] 4.3 Exception Handling and API Exception Handling in ASP. NET Web APIs

Reference page:

Http://www.yuanjiaocheng.net/webapi/create-crud-api-1-delete.html

Http://www.yuanjiaocheng.net/webapi/Consume-web-api.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-get.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-post.html

Http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-put.html

Note: This article is part of the [ASP. NET Web API series tutorial]. If this is the first time you read this series of tutorials, read the previous content first.

Exception Handling in ASP. NET Web API
Exception Handling in ASP. NET Web APIs

This article cited from: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

By Mike Wasson | March 12,201 2
Author: Mike Wasson | Date:

This article describes error and exception handling in ASP. NET Web API.
This article describes how to handle errors and exceptions in ASP. NET Web APIs:

  • HttpResponseException
  • Exception Filters
    Exception Filter
  • Registering Exception Filters
    Register an exception filter
  • HttpError
HttpResponseException

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.
What happens if an uncaptured exception is thrown by a Web API controller? By default, most exceptions are converted into an HTTP response with the 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.
The HttpResponseException (HTTP Response exception) type is a special case. This exception will return any HTTP status code you specified in the exception constructor. For example, in the following method, if the id parameter is invalid, "404-not found" is returned ".

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

For more control over the response, you can also construct the entire response message and include it with the HttpResponseException:
To control the response more, you can also construct the entire response message and use HttpResponseException to include it:

public Product GetProduct(int id) {     Product item = repository.Get(id);     if (item == null)     {         var resp = new HttpResponseMessage(HttpStatusCode.NotFound)         {             Content = new StringContent(string.Format("No product with ID = {0}", id)),             ReasonPhrase = "Product ID Not Found"         }         throw new HttpResponseException(resp);     }     return item; }
Exception Filters
Exception Filter

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. the HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
By writing an exception filter, you can customize how the Web API handles exceptions. When a controller throws an unhandled non-HttpResponseException exception, an exception filter is executed. The HttpResponseException type is a special case because it is specially designed to return 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.
The exception filter implements the System. Web. Http. Filters. IExceptionFilter interface. The simplest way to compile an exception filter is to use the System. Web. Http. Filters. ExceptionFilterAttribute class to derive and override its OnException method.

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 particle, the HandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.
Exception filters in ASP. NET Web APIs are simpler than those in ASP. net mvc. However, the two are declared in different namespaces and have independent functions. In particular, the HandleErrorAttribute class used in MVC does not handle exceptions thrown in the Web API controller.

Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
The following is a filter that converts NotImplementedException exceptions to HTTP status code 501-not implemented:

namespace ProductStore.Filters {     using System;     using System.Net;     using System.Net.Http;     using System.Web.Http.Filters;      public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute      {         public override void OnException(HttpActionExecutedContext context)         {             if (context.Exception is NotImplementedException)             {                 context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);             }         }     } }

TheResponseProperty ofHttpActionExecutedContextObject contains the HTTP response message that will be sent to the client.
HttpActionExecutedContextObjectResponseThe property contains the HTTP response message that will be sent to the client.

Registering Exception Filters
Register an exception filter

There are several ways to register a Web API exception filter:
The following methods are used to register a Web API exception filter:

  • By action
    Registered by Action
  • By controller
    Registered by the Controller
  • Globally
    Global Registration

To apply the filter to a specific action, add the filter as an attribute to the action:
To apply the filter to a specific action, add the annotation attribute of the filter to the action:

public class ProductsController : ApiController {     [NotImplExceptionFilter]    public Contact GetContact(int id)     {         throw new NotImplementedException("This method is not implemented");     } }

To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:
To apply the filter to all the actions of a controller, add the annotation attribute of the filter to the Controller:

[NotImplExceptionFilter] public class ProductsController : ApiController{    // ... }

To apply the filter globally to all Web API controllers, add an instance of the filter toGlobalConfiguration. Configuration. FiltersCollection. Exeption filters in this collection apply to any Web API controller action.
Apply the filter to all Web API controllers globally and add an instance of the filterGlobalConfiguration. Configuration. FiltersSet. The exception filter in this set applies to any Web API controller action.

GlobalConfiguration.Configuration.Filters.Add(    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 insideWebApiConfigClass, which is located in the App_Start folder:
If you are using a project created using the "ASP. net mvc 4 Web application" Project template, put your Web API configuration code inWebApiConfigClass, which is located in the App_Start Folder:

Public static class WebApiConfig {public static void Register (HttpConfiguration config ){Config. Filters. Add (new ProductStore. NotImplExceptionFilterAttribute ());// Other configuration code (Other configuration code )...}}
HttpError

TheHttpErrorObject 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) withHttpErrorIn the response body:
HttpErrorThe object provides a method for returning error messages in the response body. The following example shows how to useHttpErrorReturn the HTTP status code "404-not found" in the response body ":

public HttpResponseMessage GetProduct(int id) {     Product item = repository.Get(id);     if (item == null)     {        var message = string.Format("Product with id = {0} not found", id);         HttpError err = new HttpError(message);         return Request.CreateResponse(HttpStatusCode.NotFound, err);     }     else     {         return Request.CreateResponse(HttpStatusCode.OK, item);     } }

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 containsHttpErrorIn the request body. The response might look like the following:
In this example, if the method is successful, it will return the product in the HTTP response. However, if the requested product is not found, the HTTP response will containHttpError. The response looks like this:

HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8 Date: Thu, 09 Aug 2012 23:27:18 GMT Content-Length: 51  {   "Message": "Product with id = 12 not found" }

Notice thatHttpErrorWas serialized to JSON in this example. One advantage of usingHttpErrorIs that it goes through the same content-negotiation and serialization process as any other strongly-typed model.
Note: In this example,HttpErrorWill be serialized into JSON. UseHttpErrorOne advantage is that, like other strong-type models, the same "content negotiation" (section 6.2-Translator's note in this serialization tutorial) and serialization process will be performed.

Instead of creatingHttpErrorObject directly, you can useCreateErrorResponseMethod:
Directly create an alternativeHttpErrorYou can useCreateErrorResponseMethod:

public HttpResponseMessage GetProduct(int id) {     Product item = repository.Get(id);     if (item == null)     {         var message = string.Format("Product with id = {0} not found", id);         return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);     }     else     {         return Request.CreateResponse(HttpStatusCode.OK, item);     } }

CreateErrorResponseIs an extension method defined inSystem. Net. Http. HttpRequestMessageExtensionsClass. Internally,CreateErrorResponseCreatesHttpErrorInstance and then createsHttpResponseMessageThat containsHttpError.
CreateErrorResponseYesSystem. Net. Http. HttpRequestMessageExtensionsClass. Essentially,CreateErrorResponseCreatesHttpErrorInstance, and then createHttpErrorOfHttpResponseMessage.

HttpError and Model Validation
HttpError and Model Verification

For model validation, you can pass the model stateCreateErrorResponse, To include the validation errors in the response:
For model verification, you can pass the model statusCreateErrorResponseTo include verification errors in the response:

Public HttpResponseMessage PostProduct (Product item) {if (! ModelState. IsValid) {return Request. CreateErrorResponse (HttpStatusCode. BadRequest, ModelState);} // Implementation not shown (The Implementation code is not listed )...}

This example might return the following response:
In this example, the following response may be returned:

HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 Content-Length: 320  {   "Message": "The request is invalid.",   "ModelState": {     "item": [       "Required property 'Name' not found in JSON. Path '', line 1, position 14."     ],     "item.Name": [       "The Name field is required."     ],     "item.Price": [       "The field Price must be between 0 and 999."     ]   } }

For more information about model validation, see Model Validation in ASP. NET Web API.
For more information about model verification, see "model verification in ASP. NET Web APIs" (Section 6.4-Translator's note in this series of tutorials ).

Adding Custom Key-Values to HttpError
Add the custom "key-value" to HttpError

TheHttpErrorClass is actually a key-value collection (it derives fromDictionary <string, object>), So you can add your own key-value pairs:
HttpErrorThe class is actually a "key-value" set (derived fromDictionary <string, object>), So you can add your own "key-value" Pair:

public HttpResponseMessage GetProduct(int id) {     Product item = repository.Get(id);      if (item == null)     {         var message = string.Format("Product with id = {0} not found", id);         var err = new HttpError(message);         err["error_sub_code"] = 42;         return Request.CreateErrorResponse(HttpStatusCode.NotFound, err);     }     else     {         return Request.CreateResponse(HttpStatusCode.OK, item);     } }
Using HttpError with HttpResponseException
Use HttpError with HttpResponseException

The previous examples returnHttpResponseMessageMessage from the controller action, but you can also useHttpResponseExceptionTo returnHttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error:
The preceding example returnsHttpResponseMessageMessage, but you can also useHttpResponseExceptionTo returnHttpError. This allows you to return a strong-type model if the model is normal and successful, but still returns an errorHttpError.

public Product GetProduct(int id) {     Product item = repository.Get(id);     if (item == null)     {         var message = string.Format("Product with id = {0} not found", id);         throw new HttpResponseException(             Request.CreateErrorResponse(HttpStatusCode.NotFound, message));     }     else     {         return item;     } }

 

After reading this article, please giveRecommendation

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.