AJAX XMLHttpRequest object

jQuery Ajax error handling, show custom exception messages

Hello Guys, I am going to share the global error handling in the jQuery Ajax and trying to cover all the errors displays. The detail you can see in the example, 
//jQuery global error handling Ajax.

//#region NAMESPACE
var demo = demo || {};
//#endregion

//#region VARIABLES USED IN THIS JS
var obj_hdrs = [];
var obj = new Object();

//#endregion

//#region GLOBAL CONTEXT

demo.baseConst = {
    baseUrl: getBaseURL(),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    statusErrors : {
        'M400': "Server understood the request, but request content was invalid. [400]",
        'M401': "Unauthorized access. [401]",
        'M403': "Forbidden resource can not be accessed. [403]",
        'M404': "Requested page not found. [404]",
        'M500': "Internal server error. [500]",
        'M503': "Service unavailable. [503]",
        'M0': 'Not connect.\n Verify Network.',
        'MParsererror': 'Requested JSON parse failed. [Failed]',
        'MTimeout': 'Time out error. [Timeout]',
        'MAbort': 'Ajax request aborted. [Aborted]',
        'MUncaught': 'Uncaught Error.\n'
    }
}

//This method id used to get the base URL for global constant.

function getBaseURL() {
    var currentBaseURL = location.protocol + "//" + location.hostname +
        (location.port && ":" + location.port) + "/";
    return currentBaseURL;
};

//#endregion

//#region AJAX FUNCTIONS AND USER SESSION RELATED CODE

demo.ajax = (function () {

    //#region SET AJAX REQUEST HEADER

    var setHeaderRequest = function (xhr, arr_hdrs) {
        obj_hdrs = [];
        obj = new Object();

        // Common headers
        obj["RequestVerificationToken"] = tokenHeaderValue;

        obj_hdrs.push(obj);

        // Specific headers
        if (arr_hdrs !== undefined && arr_hdrs !== null && arr_hdrs !== '') {
            $.merge(obj_hdrs, arr_hdrs);
        }

        $.each(obj_hdrs, function (k, v) {
            $.each(obj_hdrs[k], function (i, val) {
                xhr.setRequestHeader(i, val);
            });
        });
    };

    //#endregion

    //#region AJAX ASYNC REQUEST

    var asyncCall = function (url, data, GETPOST, callback, arr_hdrs) {
        var global = demo.baseConst;

        $.ajax({
            url: global.baseUrl + url,
            type: GETPOST,
            contentType: global.contentType,
            data: data,
            beforeSend: function (xhr) {
                setHeaderRequest(xhr, arr_hdrs);
            },
            async: true,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null && data !== "") {
                    if (data.Code !== undefined && data.Code !== null && data.Code !== "") {
                        if (data.Code.toLowerCase() === "ok") {
                            callback(data);                        
                        }
                        else if (data.Code.toLowerCase() === "error") {
                            demo.dialog.alertDialog('error', 'Error', 'Error', data.Message, null);
                        }
                        else {
                            demo.dialog.alertDialog('error', 'Error', 'Error', demo.constant.request.unableToProcessYourRequest, null);
                        }
                    }                   
                    else {
                        callback(data);
                    }
                }
                else if (data === null) {
                    callback(data);
                }
                else {
                    demo.dialog.alertDialog('error', 'Error', 'Error', demo.constant.request.unableToProcessYourRequest, null);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                jqXHRError(jqXHR, errorThrown);
            }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            jqXHRError(jqXHR, errorThrown);
        });
    };

    //#endregion   

    ////#region AJAX ERROR HANDLING.
    var jqXHRError = function (jqXHR, exception) {
        var msg = '';
        var statusErrorMsg = demo.baseConst.statusErrors;

        if (jqXHR !== undefined && jqXHR !== null) {
            if (jqXHR.status === 0) {
                msg = statusErrorMsg.M0;
            }
            else if (jqXHR.status == 400) {
                msg = statusErrorMsg.M400;
            }
            else if (jqXHR.status == 401) {
                msg = statusErrorMsg.M401;
            }
            else if (jqXHR.status == 403) {
                msg = statusErrorMsg.M403;
            }
            else if (jqXHR.status == 404) {
                msg = statusErrorMsg.M404;
            }
            else if (jqXHR.status == 500) {
                msg = statusErrorMsg.M500;
            }
            else if (jqXHR.status == 503) {
                msg = statusErrorMsg.M503;
            }
            else if (exception === 'parsererror') {
                msg = statusErrorMsg.MParsererror;
            }
            else if (exception === 'timeout') {
                msg = statusErrorMsg.MTimeout;
            }
            else if (exception === 'abort') {
                msg = statusErrorMsg.MAbort;
            }
            else {
                msg = statusErrorMsg.MUncaught + jqXHR.responseText;
            }
            demo.dialog.alertDialog('error', 'Error', 'Error', msg, null);
        }
        else {
            demo.dialog.alertDialog('error', 'Error', 'Error', statusErrorMsg.MUncaught, null);
        }
    }
    ////#endregion

    return {
        asyncCall: asyncCall
    };
})();

//#endregion
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book