Web API Exception Handling

Source: Internet
Author: User

When we develop the Web API, in general, each API callback data type or format is not the same, if your project from start to finish by you alone, it may also say "Amida Buddha", but if there are other people need to share your API with you, and return the data format is not the same , I believe it will increase the user's distress, but also greatly increase the complexity of the program and maintenance difficulties. So this article also records their own experience in the practice, on the one hand to leave a record also want to help more people, waste not more say we start!

Understand the architecture and implement

I was looking for the data. Use ASP. NET MVC to build the Web API (16) – Unified input/output format and exception handling strategy, but found that the method used seems to be for ASP. NET MVC, not the Web API (I do not know the author such cognition there is no error, if there is Also trouble the predecessors to teach, and this is the thinking mode of this article is the same, just to change it to the Web API can use the method only.

As shown when a consumer requests a different API, the data is returned to the user before the page is re-packaged and then sent back to the consumer, so that the data format that users see is fixed.

1. So first we need to customize a Model to be used as a container for our packaging, whose categories are defined as follows:

public class Apiresultmodel
{
    Public HttpStatusCode Status {get; set;}
    Public object Data {get; set;}
    public string ErrorMessage {get; set;}
}

2. Believe that friends who have written ASP. NET MVC will know that in general we will put some logic fixed in Action, using the Filter to apply to each action, for example: authorize. If you are not familiar with Filter, refer to the article written by predecessors on the network: [VS2010] ASP. NET MVC with Action Filters. So here we also need to use the same technique to repackage the data format of our callback, we first add a ApiResultAttribute.cs file, and inherit System.Web.Http.Filters.ActionFilterAttribute, and the method of copying onactionexecuted, as follows:

public class ApiResultAttribute:System.Web.Http.Filters.ActionFilterAttribute
{
       public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext)
       {
            Base. OnActionExecuted (ActionExecutedContext);     
       }
}

3. onactionexecuted will call after Action execution, also means that we send the data into this method, and then deal with our main package of program logic, the program code is as follows:

public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext)
{
    Base. OnActionExecuted (ActionExecutedContext);
    Apiresultmodel result = new Apiresultmodel ();
    Gets the status code returned by the API
    Result. Status = ActionExecutedContext.ActionContext.Response.StatusCode;
    Get the data returned by the API
    Result. Data = Actionexecutedcontext.actioncontext.response.content.readasasync<object> (). Result;
    Re-encapsulate callback format
    Actionexecutedcontext.response = ActionExecutedContext.Request.CreateResponse (result. Status, result);
}

4. In order for all Web APIs to be able to apply our custom filter, we need to app_start→webapiconfig.cs→register to register the global Web API filter. (Note: To register the Web API, the Filter needs to be registered in WebApiConfig.cs, not FilterConfig.cs)

Config. Filters.add (New Apiresultattribute ());

5. After re-building, we re-execute the original Web API program, we will see the callback format has become our custom format:

"Status": 200,
    "Data": [
        {
            "Account": "Taxi",
            "Mark": "",
            "Name": "Taming Wang Speaking",
            "Telephone": "0986540123",
            "Accountstatus": True
        },
        {
            "Account": "Taxi2",
            "Mark": "",
            "Name": "Square Datong",
            "Telephone": "0922335111",
            "Accountstatus": True
        },
        {
            "Account": "q121234567",
            "Mark": null,
            "Name": "0000",
            "Telephone": "0972334334",
            "Accountstatus": True
        }
    ],
    "ErrorMessage": null

Exception handling

We have already packaged the message in the format we want, but we have not yet dealt with the exception program code, generally when the program has an exception to the error, we also hope that the receiver can know the program error, and then display the message, instead of watching the program Crash Or a pause, which will give your client a bad experience, and in ASP. Exceptionfilterattribute, which specifically deals with exceptions, let's take a look at how to package our exception messages.

1. Add a ApiErrorHandleAttribute.cs and inherit the System.Web.Http.Filters.ExceptionFilterAttribute, then replicate Onexception When an exception occurs, the code of the program executes as follows:

public class ApiErrorHandleAttribute:System.Web.Http.Filters.ExceptionFilterAttribute
{
       public override void Onexception (System.Web.Http.Filters.HttpActionExecutedContext actionexecutedcontext)
       {
           Base. Onexception (ActionExecutedContext);
       }
}

2. The onexception approach allows us to capture what happens when an exception occurs, and we also record the time of the error, the logged-in user, and the status of the error (for example: System event, database, write. txt file). And so on, but this is not the point of our discussion, let's take a look at how to package our exception message, the program code is as follows:

public override void Onexception (System.Web.Http.Filters.HttpActionExecutedContext actionexecutedcontext)
{
    Base. Onexception (ActionExecutedContext);
    
    Get an error message when an exception occurs
    var errormessage = actionExecutedContext.Exception.Message;
    var result = new Apiresultentity ()
    {
        Status = Httpstatuscode.badrequest,
        ErrorMessage = errormessage
    };
    Re-package the callback message
    Actionexecutedcontext.response = Actionexecutedcontext.request
        . Createresponse (result. Status, result);
}

3. And because the program throws the exception will first go back to onactionexcuted in the exception of processing, so we slightly modify the original onactionexcuted this method, so that the exception will be skipped directly on this side of the packaging of our message, the program code is as follows:

public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext)
{
    If an exception occurs, do not handle it here.
    if (actionexecutedcontext.exception! = null)
    Return
    
    Base. OnActionExecuted (ActionExecutedContext);
    Apiresultmodel result = new Apiresultmodel ();
    Gets the status code returned by the API
    Result. Status = ActionExecutedContext.ActionContext.Response.StatusCode;
    Get the data returned by the API
    Result. Data = Actionexecutedcontext.actioncontext.response.content.readasasync<object> (). Result;
    Re-encapsulate callback format
    Actionexecutedcontext.response = ActionExecutedContext.Request.CreateResponse (result. Status, result);
}

3. Then we want to register this custom filter with the program, so we can register our filter with App_start→webapiconfig.cs→register:

Config. Filters.add (New Apierrorhandleattribute ());

4. After the re-establishment, when the exception of our program will be in accordance with our format back to the user:

{
    "Status": 400,
    "Data": null,
    "ErrorMessage": "Try to divide with 0." "
}

Summarize

In this way we have successfully solved a simple case, but here also need to remind the reader, generally in dealing with the exception here is not directly to the exception message to the user, because if you assume that the exception you threw today contains some more sensitive information, such as: database name or data table name ... And so on, so that your program is indirectly a loophole, so if you really want to use this program code remember the following exception to capture the other side of the packaging.

Web API exception Handling (GO)

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.