This article main reference: Http://www.asp.net/web-api/overview/error-handling/exception-handling
1. If a Web API controller throws an uncaught exception, by default, most exceptions are converted to an HTTP response status code of 500 internal server error.
The httpresponseexception type is a special case. This exception returns any HTTP status codes that are specified in the exception constructor. For example, the following method if the parameter ID is invalid, the request returns 404.
Public Product getproduct (int ID) { = repository. Get (ID); if NULL { thrownew httpresponseexception (httpstatuscode.notfound); } return item;}
Of course you can also build a complete response message through httpresponseexception.
PublicProduct GetProduct (intID) {Product Item=Repository. Get (ID); if(Item = =NULL) { varRESP =NewHttpresponsemessage (httpstatuscode.notfound) {Content=NewStringcontent (string. Format ("No product with ID = {0}", id)), reasonphrase="Product ID not Found" } Throw Newhttpresponseexception (RESP); } returnitem;}
Exception filter
You can crawl all unhandled exceptions by customizing an exception filter. Of course, excluding exceptions of type httpresponseexception , it is a special case because it returns an HTTP message directly.
The exception processor inherits from the System.Web.Http.Filters.IExceptionFilter interface. The quickest way to create a new exception handler is to inherit the System.Web.Http.Filters.ExceptionFilterAttribute class and override the (override) Onexception method.
Exception handlers in the Web API are very similar to exception handlers in MVC, although they come from different namespaces and functions.
The following example implements an exception filter that converts an notimplementedexception exception to an HTTP 501 error.
namespaceproductstore.filters{usingSystem; usingSystem.Net; usingSystem.Net.Http; usingSystem.Web.Http.Filters; Public classNotimplexceptionfilterattribute:exceptionfilterattribute { Public Override voidonexception (Httpactionexecutedcontext context) {if(Context. Exception isnotimplementedexception) {context. Response=Newhttpresponsemessage (httpstatuscode.notimplemented); } } }}
How do I register these custom exception handlers?
The system provides the following three ways to register
1, action on the registration
Public class productscontroller:apicontroller{ [notimplexceptionfilter] Public contact getcontact ( int ID) { thrownew notimplementedexception ("This method was notimplemented "); }}
2, register on the controller
[Notimplexceptionfilter] Public class productscontroller:apicontroller{ Public Contact GetContact (int ID) { thrownew notimplementedexception ("This method was notimplemented " ); }}
3. Global Registration
Public Static class webapiconfig{ publicstaticvoid Register (httpconfiguration config) { config. Filters.add (new Productstore.notimplexceptionfilterattribute ()); // Other configuration code ... }}
Httperror
The Httperror object provides a consistent method for returning an error message in an HTTP response message, and here is an example of returning a 404 error in an HTTP response message:
PublicHttpresponsemessage GetProduct (intID) {Product Item=Repository. Get (ID); if(Item = =NULL) { varMessage =string. Format ("Product with id = {0} not found", id); returnrequest.createerrorresponse (httpstatuscode.notfound, message); } Else { returnrequest.createresponse (Httpstatuscode.ok, item); }}
The following example shows how to return the model validation error message via Httperror
Public httpresponsemessage postproduct (Product item) { if (! Modelstate.isvalid) { return request.createerrorresponse ( Httpstatuscode.badrequest, modelstate); } // implementation not shown...}
Httpresponseexception and Httperror used together
PublicProduct GetProduct (intID) {Product Item=Repository. Get (ID); if(Item = =NULL) { varMessage =string. Format ("Product with id = {0} not found", id); Throw Newhttpresponseexception (Request.createerrorresponse (httpstatuscode.notfound, message)); } Else { returnitem; }}
Exception handling in the ASP. NET Web Api