简体   繁体   中英

How to handle internal server error in ajax response

When I send an Ajax request in JavaScript (with JQuery), it sometimes throws an internal server error that I can't catch. The error shows up in the browser. I even tried to wrap the ajax call in a try - catch block. How can I handle the Ajax error?

EDIT here is my code:

$.post('/multi/getGameStatus', function(data) {
    if(data && data.game) {
        settings.game = data.game;
        setStartRacePopupUI.call(this, data);
        // remove all racers
        removePlayers.call();
        for(var i=0;i<settings.game.players.length;i++) {
            var player = settings.game.players[i];
            var isme = (player.id == settings.playerId);
            addPlayer.call(this, player, isme, i);
        }

        if (settings.game.gameStatus == "OPEN") {
            setTimeout(refreshPlayers, refreshPlayersInterval, nextStatus);
        } else if(settings.game.gameStatus == "IN_GAME") {
            counterToGameStart = data.sts;
            gameFllow(nextStatus);
        }
    }
});

Even if I use the error handler I still get a JS error on the page

http://api.jquery.com/jQuery.ajax/

...For convenience and consistency with the callback names used by $.ajax(), jqXHR also provides .error(), .success(), and .complete() methods.

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "example.php" )
    .done(function() { alert("success"); })
    .fail(function() { alert("error"); })
$.ajax({
  url:"myurl",
  data: {json:"data"},
  success: function(){//on success},
  error: function(){//called on error}
});

error callback as per ajax api docs : (when in doubt refer to api docs)

error(jqXHR, textStatus, errorThrown)Function

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM