Web api--handling of custom exception results

Source: Internet
Author: User
Tags tojson try catch

1. General Exception Handling

Uniform exception handling, it is important to return the correct information to the caller, so that the interface developer or user can understand the specific reason, so that the error can be handled effectively.

Reference API processing, API, for calls have an error message returned, will not directly bare the unhandled exception, so they are a certain interception processing, and then the error message wrapper to the interface caller. Some interfaces handle errors as follows.

An error code, such as an error message, is returned as an example of a JSON packet (the example is AppID invalid error): {"Errcode": 40013, "errmsg": "Invalid AppID"}

We define a unified error information entity class, as shown below, according to our own needs.

    <summary>///    interface returned error messages///    </summary> public    class Baseresultjson {//        < summary>///error code///        </summary> public        int Errcode {get; set;}        <summary>///        if unsuccessful, return error message///        </summary> public        string ErrMsg {get; set;}        <summary>//whether successful///        </summary> public        bool Success {get; set;}    }

This allows us to convert the intercepted error message into such a handy entity class information.

Interception of the Web API call exception, the general can be combined with the method of Try catch, as well as the exception interceptor to deal with, the following is the active throw some exception information processing.

            If not passed, throws an exception, handled uniformly by the exception filter            if (!result.success)            {                throw new myapiexception(result.errmsg , Result.errcode);            }

Where Myapiexception is a custom exception information that is used to host custom error messages for the exception class.

Exception blocker, which we can handle in the Web API by attribute this tag feature, I define an exception handler in the base class of the Web API.

    <summary>///    All Interface base classes///    </summary>    [exceptionhandling] public    class Baseapicontroller:apicontroller

The definition of this attribute object, its code is shown below.

    <summary>///API custom Error Filter Properties///</summary> public class Exceptionhandlingattribute:exceptio Nfilterattribute {//<summary>/////For processing of calling exception information, returning custom exception information///</summary>// /<param name= "context" >http contextual object </param> public override void Onexception (Httpactionexecutedcontext Co ntext) {//Custom exception handling Myapiexception ex = context.            Exception as Myapiexception; if (ex! = null) {throw new Httpresponseexception (new Httpresponsemessage (httpst Atuscode.internalservererror) {//encapsulation handles exception information, returns the specified JSON object Content = new S Tringcontent (New Baseresultjson (ex. Message, False, Ex.errcode).            ToJson ()), reasonphrase = "Exception"}); }//Record critical exception information Debug.WriteLine (context.                        Exception); Handling of generic exceptions stringmsg = string. IsNullOrEmpty (context. Exception.Message)? "There was an error in the interface, please retry or contact the Administrator": Context.            Exception.Message; throw new Httpresponseexception (new Httpresponsemessage (httpstatuscode.internalservererror) {Co        ntent = new Stringcontent (msg), Reasonphrase = "Critical Exception"}); }    }

Based on this code, we can implement the uniform encapsulation of the invocation exception, let it return to us the unified object information, the following is one of the call exception, converted to custom exception information after the output of the result.

{"Errcode": 404, "ErrMsg": "The requested resource does not support HTTP method" POST ". "," Success ": false}

This way we can handle the return results of the Web API by processing its exception information, as shown in the following code.

            Httphelper helper = new Httphelper ();            Helper. ContentType = "Application/json";            String content = Helper. gethtml (URL, postdata, true);            Verifyerrorcode (content);            T result = jsonconvert.deserializeobject<t> (content);            return result;

Our code in the Red section above is to deal with the exception definition information, if there are these exceptions, we can be in the interface for exception processing display.

For example, if a custom exception exists, we convert it, display the corresponding information, and re-throw the exception.

                Baseresultjson Errorresult = jsonconvert.deserializeobject<baseresultjson> (content);                The non-successful operation logged the exception because some operations returned a normal result ({"Errcode": 0, "errmsg": "OK"})                if (errorresult! = NULL &&!). errorresult.success)                {                    string error = String. Format ("The request has an error! Error code: {0}, Description: {1} ", (int) errorresult.errcode, errorresult.errmsg);                    Logtexthelper.error (Errorresult.tojson ());                    throw new Exception (error);//Throw Error                }

2, address interface exception handling

For the general exception, we can be very good interception and processing through the above processing, if the interface exception is global, such as access to the address book is correct, or the parameters of a few more information, then the interface is not a valid address, so that the information returned will not be processed by the above interceptor.

If we give an invalid API call path, we get the following error result in the browser.

The above results cannot be captured by our regular exception interceptors, so the encapsulated exception information is not output.

If interception is required, we need to add our own message agent processing to capture these special exception information.

    public static class Webapiconfig    {public        static void Register (httpconfiguration config)        {                ..............            Customerrormessagedelegatinghandler ());

The red part above is the message agent processing class We added to handle some special exception information, as shown in the following code.

    <summary>///API custom error message processing delegate class.    Used to handle situations where the corresponding API address is not accessible, and to customize the operation of the error. </summary> public class Customerrormessagedelegatinghandler:delegatinghandler {protected Overrid            E task

After the above processing, we further test the non-existent address of the exception processing results, you can see the content of the output is a custom object conversion.

General invocation, if the interface does not correspond, then the error is similar to the following message

{"Errcode": 404, "errmsg": "Cannot find with request URI" http://localhost:9001/api/SystemType/Delete?signature= 72f8d706c79dc14d70fc3f080d4706748d754021&timestamp=1443194061&nonce=0.650359861855563&appid= website_9a39c2a8&token= Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjpc3mioiixiiwiawf0ijoxndqzmtk0mdm4lcjqdgkioii1ymeyyme5ni0yzta4ltq1ztgtytawny01mmy3 Otkzytg2nzeilcjuyw1lijoiywrtaw4ilcjjagfubmvsijoimcisinnoyxjlzgtlesi6ijeymzrhymnkin0.rrxqmmscjzdk5or6rmbl5wjd-yijoeqfc0poz Qhr6iu "matches the HTTP resource. "," Success ": false}

With this information, we can unify our call rules, and make exception records and display, very convenient.

Http://www.cnblogs.com/wuhuacong/p/4843422.html

Web api--handling of custom exception results

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.