Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 278
Yoav A Avatar asked Oct 28 '25 09:10

Yoav A


1 Answers

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"); })
like image 60
CD.. Avatar answered Oct 30 '25 00:10

CD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!