Quantcast
Channel: jQuery Library for SharePoint Web Services
Viewing all articles
Browse latest Browse all 6517

New Post: SPServices Error Handling

$
0
0
Thanks @ptavares I used your code as a starting point for my own error handling.

Before I share my "generic" SPServices error handling I've come up with that works for me, I'd like to remind everyone of why this isn't already built into SPServices. See Marc Anderson's blog post Generic Error Handling in SPServices

That said, here the code I'm using:
// PURPOSE://  Examines SPServices xData.responseXML for any errors. At a minimum, it will use this SP.UI framework to display//  an error summary in the status bar which can include the name of your function and the SPServices operation for //  troubleshooting in the field and debugging during development. Optionally, it dumps the verbose output from //  $().SPServices.SPDebugXMLHttpResult() to a supplied container//// NOTE://  It is possible for the "Status" parameter in the completefunc() callback to state "success" and for//  xData.statusText to hold "OK" when in fact there are errors. A "Status" of "success" simply means the web //  service call succeeded. It does NOT mean the web service did not return its own error code and message.//// USAGE://  $(xData).OutputSPError();//
jQuery.fn.OutputSPError = function(options) {

    var opt = $.extend({}, {
        functionName:   "",             // Name of your javascript function that invoked the SPServices call
        operationName:  "",             // Name of the SPServices operation, ie: "UpdateListItems"
        msgContainer:   "#SPServices",  // [OPTIONAL] jQuery selector for HTML container to hold error messages output
        }, options);
    
    // Ensure we were chained to the right objectif( typeof($(this).prop("responseXML")) === "undefined" )
        return;

    var responseXML = $(this).prop("responseXML");
    if( !$(responseXML).hasSPError() )
        return;
    
    var statusText  = $(this).prop("statusText");
    var message = "";

    if( opt.functionName != "" || opt.operationName != "" )
        message = "[" + opt.functionName + "] " + opt.operationName + " :: ";

    // Display the error summary in the status barvar strStatusID = 
        SP.UI.Status.addStatus(
            "<img src='/_Layouts/Images/error16by16.gif' align='absmiddle'>&nbsp;" + 
            message + (statusText != "OK" ? statusText + ":&nbsp;" : "" ) + $(responseXML).getSPErrorText());
    SP.UI.Status.setStatusPriColor(strStatusID, "yellow");

    // Dump the error details to the caller's message container and unhide itif( $(opt.msgContainer).length != 0 ) {
        var errorDetails    = $().SPServices.SPDebugXMLHttpResult({node: responseXML});
        var divStatus       = jQuery("<h1 class='_wsStatusText'></h1>").appendTo(opt.msgContainer);
        var divError        = jQuery("<div class='_wsError'></div>").appendTo(opt.msgContainer);
        $(divStatus).text((statusText != "OK" ? statusText : $(responseXML).getSPErrorCode()));
        $(divError).append("<b>" + message + "</b><br>" + errorDetails);
        $(opt.msgContainer).show();
    }
    return;
}


// PURPOSE://  Given an XML message as returned by the Sharepoint web services API, this method checks for an error//// RETURNS://  {Boolean} true|false//// USAGE://  $(xData).hasSPError();//  $(xData.responseXML).hasSPError();//
jQuery.fn.hasSPError    = function() {

    // Sometimes a web service will be reachable and the web method will still// return an error code XML node. So we need to check its contentsreturn( $(this).getSPErrorCode() != "0x00000000");
};/* jQuery.fn.hasSPError() */// PURPOSE://  Given an XML message as returned by the Sharepoint web services API, this method//  checks if it contains an error and returnS the error code.//// NOTE://  Sometimes a web service will be reachable and the web method call will succeed with no errors//  but it may still return an error code XML node. If so, the node value needs to be checked.//  EXAMPLE: UpdateListItems returns "0x00000000" for success//// RETURNS://  {String} hexidecimal error code//// USAGE://  $(xData).hasSPError();//  $(xData.responseXML).hasSPError();//
jQuery.fn.getSPErrorCode    = function() {

    var responseXML = $(this).prop("responseXML");
    if( typeof($(this).prop("responseXML")) === "undefined" )
        responseXML = $(this);

    var spErrCode = $(responseXML).find("ErrorCode:first");
    if( spErrCode.length )
        return spErrCode.text();
    
    spErrCode = $(responseXML).find("errorcode:first");
    if( spErrCode.length )
        return spErrCode.text();
    
    spErrCode = $(responseXML).find("faultcode");
    if( spErrCode.length )
        return spErrCode.text();
    
    return"0x00000000";
};/* jQuery.fn.hasSPError() */// PURPOSE:// Given a sharepoint webservices response, this method will look to see if it // contains an error and return that error formated as a string.//// RETURNS://  {String} error message text//// USAGE://  alert($(xData).getSPError());//  alert($(xData.responseXML).getSPError());//
jQuery.fn.getSPErrorText    = function(){

    var responseXML = $(this).prop("responseXML");
    if( typeof($(this).prop("responseXML")) === "undefined" )
        responseXML = $(this);

    var errorText   = "Call to Sharepoint web services failed. ";
    
    if( $(responseXML).find("ErrorCode:first").text().length ) {
        errorText += "\n" + $(responseXML).find("ErrorCode:first").text()
            +   ": " + $(responseXML).find("ErrorText").text();
    } elseif( $(responseXML).find("faultcode").length ) {
        errorText += $(responseXML).find("faultstring").text()
            + "\n" + $(responseXML).find("errorstring").text();
    } else {
        errorText = "";
    }
    return errorText;
}/* jQuery.fn.getSPError() */
And here is an example of how you might use it:
var spsReturn   = $().SPServices({
    operation: "UpdateListItems",
    listName: $().SPServices.SPListNameFromUrl(),
    ID: myListItemID,
    valuepairs: [["ContentType", "Journal Entry"]], // Upon submission, all journal entries use the same content type
    completefunc: function(xData, Status) {
        if( $(xData).hasSPError() ) {
            // FAILURE: Either we couldn't reach the web service or the web method DID return an error
            $(xData).OutputSPError({functionName:   "PreSaveAction",
                        operationName:  "UpdateListItems",
                        msgContainer:   "#SPServices"});
        } else {
            // SUCCESS: Able to reach the web service and the web method did NOT return an error
        }
    }
});

// We can check for the success or failure of the SPServices() call outside the completefunc()if( $(spsReturn).hasSPError() ) {
    // Business logic for when the web service/method fails
}
Output from failure to reach the web service:
Image

Output from the web method UpdateListItems returning an error:
Image

Viewing all articles
Browse latest Browse all 6517

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>