C # Advanced--WEBAPI exception handling mechanism

Source: Internet
Author: User
Tags microsoft website

In fact, for C # exception handling everyone is not unfamiliar, but for WEIAPI on the exception handling in fact and the traditional exception processing is not very different, but through encapsulation can make the exception more friendly, https://docs.microsoft.com/en-us/aspnet/ Web-api/overview/error-handling/exception-handling, through Microsoft's official introduction, we can know that WEIAPI can be briefly summarized as three kinds of anomalies, and then we give an example around these three kinds of exceptions, How to encapsulate and handle the above three types of exceptions

Exception filtering

The exception filter implements System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write exception filters is from the System.Web.Http.Filters.ExceptionFilterAttribute class derived and rewrite onexception method. Microsoft gives an explanation of the exception filter, so how to do it? By reading the "ASP. NET WEB API2 Framework", we know that every client request API will be response to the client via HTTP requests, and the server gets the result output. In this process, once an exception occurs on the server, a 500 error is returned to the client uniformly.

How do I define it in the Web API? NotImplementedException class? First create a new class WebApiExceptionFilterAttribute.cs in App_start, inherit Exceptionfilterattribute, override Onexception method, code as follows

1  Public classWebapiexceptionfilterattribute:exceptionfilterattribute2     {3         //overriding the exception handling method for a base class4          Public Override voidonexception (httpactionexecutedcontext actionexecutedcontext)5         {6             //1. Abnormal log records (usually in the official project with Log4net log exception logs)7Console.WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"--"+8ActionExecutedContext.Exception.GetType (). ToString () +":"+ ActionExecutedContext.Exception.Message +"--Stack information:"+9 actionExecutedContext.Exception.StackTrace);Ten  One             //2. Return caller-specific exception information A             if(actionexecutedcontext.exception isnotimplementedexception) -             { -Actionexecutedcontext.response =Newhttpresponsemessage (httpstatuscode.notimplemented); the             } -             Else if(actionexecutedcontext.exception istimeoutexception) -             { -Actionexecutedcontext.response =Newhttpresponsemessage (httpstatuscode.requesttimeout); +             } -             //..... Here you can return to the client-specific status code based on your project needs. If the corresponding exception is not found, the Unified return server error +             Else A             { atActionexecutedcontext.response =Newhttpresponsemessage (httpstatuscode.internalservererror); -             } -  -             Base. Onexception (actionexecutedcontext); -         } -}
View Code

Code parsing: By judging the specific type of exception, to return different HTTP status code to the client, the sample written two, according to the actual situation of the project to add some specific we want to catch the exception, and then write the corresponding status code to the HTTP request response inside, For some exceptions where we cannot judge the type, we return the service-side error 500 uniformly. Microsoft also has a code implementation, but no encapsulation

Registering Exception filtering

There are several ways to register the Web API exception filter:

    • Interface level
    • Controller level
    • Global configuration

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

public class productscontroller:apicontroller{    [notimplexceptionfilter] public contact    getcontact (int id)    {        throw new NotImplementedException ("This method was not implemented");}    }

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

[Notimplexceptionfilter]public class productscontroller:apicontroller{    //...}

  to apply the filter globally to all Web API controllers, add the filter instance to the GlobalConfiguration.Configuration.Filters the collection. The execution filters in this collection apply to any Web API controller operation.

GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (    new Productstore.notimplexceptionfilterattribute ());

If necessary, you can even write a custom description to the status code, and you can write the information we want to our response content. Let's change the Onexception method a little bit:

if (Actionexecutedcontext.exception is notimplementedexception)            {                var oresponse = new Httpresponsemessage ( httpstatuscode.notimplemented);                Oresponse.content = new Stringcontent ("Method not supported");                Oresponse.reasonphrase = "This Func was not supported";                Actionexecutedcontext.response = Oresponse;            }
Httpresponseexception Custom Exception information

Exception filters are for interface controllers and globally defined, and generally return server-level errors, but sometimes we need to define the code of the business exception, so if it is a business exception we can use the Httpresponseexception custom exception, such as the following code:

 PublicProduct GetProduct (intID) {Product Item=Repository.    Get (ID); if(Item = =NULL)    {        varRESP =NewHttpresponsemessage (httpstatuscode.notfound) {Content=NewStringcontent (string. Format ("No product foundproduct with ID = {0}", id)), reasonphrase="Product ID not Found"        }        Throw Newhttpresponseexception (RESP); }    returnitem;}

You can see that the specific business exception information is encapsulated through the httpresponsemessage, and finally thrown by httpresponseexception, Microsoft does not explain what httpresponsemessage is, At first I thought this was a httpresponseexception subclass, but after tracking it, I found Httpresponsemessage inherited the IDisposable interface, and IDisposableThe primary purpose of an interface is to release unmanaged resources.The garbage collector automatically frees the memory that is allocated to managed objects when the object is no longer being used. However, it is not possible to predict that a garbage collection will occur. In addition, the garbage collector has unmanaged resources that do not know such as window handles, or open files and streams. From the description of the use of Httpresponsemessage represents an exception occurred and a resource management of the recycling, so I think, the use of httpresponsemessage can be more clearly described in the business of the exception that occurs, And a garbage collection when returning an exception, reducing the waste of program resources

Httperror

the httperror object provides a consistent way to return an error message in the body of the response. The following example shows how to use httperror in the response body to return an HTTP status code 404 (not Found) . With Microsoft's explanation, you know that Httperror provides a status code return, so the actual application is to use it with httpresponseexception.

 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; }}
Summarize

Using C # Advanced Series--webapi Exception handling solution,

Learn about exception handling in ASP. NET Web API (Microsoft website)

In a general project, you can define some of the entire server-side exception handling, and encapsulate good one httpresponseexception custom exception handling, without catching httpresponseexception exceptions, the API will handle this exception itself, And it is better to give each exception a more detailed HTTP status code, can make the exception more sophisticated and friendly

C # Advanced--WEBAPI exception handling mechanism

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.