Question

I have a jqgrid that's functionning very well.

I was wondering is it possible to catch server sent errors ? how Is it done ?

Was it helpful?

Solution

I have recently made extensive use of jqgrid for a prototype project I am working on for CB Richard Ellis (my employer). There are many way to populate a jqgrid, as noted in the documentation: (see the "retrieving data" node).

Currently I make a service call that returns a json string that when evaluated, gives me an object that contains the following:

  • ColumnNames: string[]
  • ColumnModels: object[] (each object has the properties "name", "index" and "sortable")
  • Data: object[] (each object has properties that match the names in the column model)
  • TotalRows: int

In my success callback, I manually create the jqgrid like this: ("data" is the object I get when evaluating the returned json string).

var colNames = data.ColumnNames;
var colModel = data.ColumnModels;
var previewData = data.PreviewData;
var totalRows = data.TotalRows;
var sTargetDiv = userContext[0]; // the target div where I'll create my jqgrid

$("#" + sTargetDiv).html("<table cellpadding='0' cellspacing='0'></table>");
var table = $("#" + sTargetDiv + " > table");
table.jqGrid({
    datatype: 'local',
    colNames: colNames,
    colModel: colModel,
    caption: 'Data Preview',
    height: '100%',
    width: 850,
    shrinkToFit: false
});

for (var row = 0; row < previewData.length; ++row)
    table.addRowData(row, previewData[row]);

So you can see I manually populate the data. There is more than 1 kind of server error. There is the logical error, which you could return as a property in your json string, and check before you try to create a jqgrid (or on a per-row basis).

if (data.HasError) ...

Or on a per-row basis

for (var row = 0; row < previewData.length; ++row)
{
    if (previewData[row].HasError)
        // Handle error, display error in row, etc
        ...
    else
        table.addRowData(row, previewData[row]);
}

If your error is an unhandled exception on the server, then you'll probably want an error callback on your async call. In this case, your success callback that (presumably) is creating your jqgrid won't be called at all.

This, of course, applies to manually populating a jqgrid, which is only one of the many options available. If you have the jqgrid wired directly to a service call or a function to retrieve the data, then that's something else entirely.

On the documentation page, look under Basic Grids > Events. There you'll see the "loadError" event that might come in handy.

OTHER TIPS

If you look at the jqgrid demo site and look at "What's new in version 3.2" There should be a section about controlling server errors.

Specifically, it uses a callback parameter loadError:

loadError : function(xhr,st,err) { 
    jQuery("#rsperror").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
}

As mcv states above, some errors are data errors, so you'll need to handle those specifically.

Use the callbacks. If you get an actual http error (a 400 or 500, for example), loadError(xhr, status, error) is triggered.

But some errors (like validation) shouldn't throw a 400 or 500 error. But you can still catch those in loadComplete(xhr). Parse your json, and check for whatever way you're using to identify errors. For example, I'm doing this in my loadComplete():

if (jsonResponse.errors) { $.each(jsonResponse.errors, function(i, val){ addErrorMessage($("#"+val.field), val.message); }); }

You can use the loadError event in jqGrid definition (see documentation). E.g.:

//Catch errors
loadError = function(xhr, textStatus, errorThrown)  {
    var error_msg = xhr.responseText        
    var msg = "Some errors occurred during processing:"
    msg += '\n\n' + error_msg
    alert(msg)
    }

From what I see, it returns the data as a json string. So what you have to do is add an error handler that formats the error as a json string and prints it out as one. This can be done in php with the

set_error_handler

function.

The error handler would then I guess push the data in to jsonReturn.error, so you would just need to check for that when you are adding your data to the table.

If you are throwing exceptions instead of letting it get all the way to errors (probably a better practice), then you would want to format the exception as a json string.

Since it is returning the data in an xml format, you would want to parse the xml:

<xml>
    <error>
        error message
    </error>
</xml>

like this:

$(request.responseXML).find("error").each(function() {
        var error = $(this);
        //do something with the error
});

Shamelessly borrowed from: http://marcgrabanski.com/article/jquery-makes-parsing-xml-easy

Another thing to remember/ or that I found is that if you are using Asp.net you need to turn

in the section - this will allow you to introspect the Message coming back as well.

If you're using jqGrid with the options

            ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
            datatype: "json",
            url: wsPath

to load data via AJAX and web services or MVC controllers, then this answer is for you.

Note that if a runtime error occurs in the web method dealing with the AJAX call, it can't be catched via loadError, because loadError only catches HTTP related errors. You should rather catch the error in the web method via try ... catch, then pass it in JSON format in the catch block using return JsonString. Then it can be handled in the loadComplete event:

loadComplete: function (data) {
                    if (this.p.datatype === 'json') {
                        if (data!==undefined && data!==null && isErrorJson(data)) {
                            ShowErrorDialog(getJsonError(data));
                        }
                // ...
              }

The functions above have the following meaning, implement them as needed:

  • isErrorJson(data): returns true, if the data object contains error as defined in your web method
  • getJsonError(data): returns the string with the error message as defined in your web method
  • ShowErrorDialog(msg): displays the error message on screen, e.g. via jQueryUI dialog.

In the web service method you can use JavaScriptSerializer to create such an error object, for the 2 JavaScript methods above you can use the jQuery function $.parseJSON(data.d) to get the message out of the JSON object.

function gridCroak(postdata, _url, grid, viewCallBack, debug) {
$(".loading").css("display", "block");
$.ajax({
    type: 'POST',
    url: _url,
    data: postdata,
    dataType: "xml",
    complete: function(xmldata, stat){
    if(stat == "success") {
        $(".loading").css("display", "none");
        var errorTag = xmldata.responseXML.getElementsByTagName("error_")[0];
        if (errorTag) {
        $("#ErrorDlg").html(errorTag.firstChild.nodeValue);
        $("#ErrorDlg").dialog('open');
        } else {
        var warningTag = xmldata.responseXML.getElementsByTagName("warning_")[0]; 
        if (warningTag) {
            $("#WarningDlg").html(warningTag.firstChild.nodeValue);
            $("#WarningDlg").dialog('open');
        } else {
            if (debug == true) {
            alert(xmldata.responseText);
            }
            jQuery(grid)[0].addXmlData(xmldata.responseXML);
            if(viewCallBack) viewCallBack();
        }
        }
    } else {
        $("#ErrorDlg").html("Servizio Attualmente Non Disponibile !");
        $("#ErrorDlg").dialog('open');
    }
    }
});
}

And In the Grid

datatype : function(postdata) { gridCroak(postdata, 'cgi-bin/dummy.pl?query=stock', 
                                                    "#list", null, false) },

At the end it does use the same approach I think.

Thanks all

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top