Обработать 500 ошибок в JSON (jQuery)

Этот запрос JSON:

$.ajax({
    url:jSONurl+'?orderID='+thisOrderID+'&variationID='+thisVariationID+'&quantity='+thisQuantity+'&callback=?',
    async: false,
    type: 'POST',
    dataType: 'json',
    success: function(data) {
        if (data.response == 'success'){
            //show the tick. allow the booking to go through
            $('#loadingSML'+thisVariationID).hide();
            $('#tick'+thisVariationID).show();
        }else{
            //show the cross. Do not allow the booking to be made
            $('#loadingSML'+thisVariationID).hide();
            $('#cross'+thisVariationID).hide();
            $('#unableToReserveError').slideDown();
            //disable the form
            $('#OrderForm_OrderForm input').attr('disabled','disabled');
        }
    },
    error: function(data){
        alert('error');
    }
})

В определенных обстоятельствах будет возвращена ошибка 500 в виде:

jQuery17205593111887289146_1338951277057({"message":"Availability exhausted","status":500});

Это, однако, по-прежнему полезно для меня, и мне нужно иметь возможность справиться с этим правильно.

Почему-то, когда эта ошибка 500 возвращается, моя функция ошибки не вызывается, и я просто получаю сообщение об ошибке "Внутренняя ошибка сервера NetworkError: 500" в firebug.

Как я могу справиться с этим?

Ответы

Ответ 1

Вы пытались выполнить statuscode обратный вызов, например

 $.ajax({
    statusCode: {
        500: function() {
          alert("Script exhausted");
        }
      }
   });

Ответ 2

Я думаю, вы можете поймать его, добавив это:

$.ajax({
    statusCode: {
      500: function() {
      alert("error");
       }
    },
    url:jSONurl+'?orderID='+thisOrderID+'&variationID='+thisVariationID+'&quantity='+thisQuantity+'&callback=?',
    async: false,
    type: 'POST',
    dataType: 'json',
    success: function(data) {
        if (data.response == 'success'){
            //show the tick. allow the booking to go through
            $('#loadingSML'+thisVariationID).hide();
            $('#tick'+thisVariationID).show();
        }else{
            //show the cross. Do not allow the booking to be made
            $('#loadingSML'+thisVariationID).hide();
            $('#cross'+thisVariationID).hide();
            $('#unableToReserveError').slideDown();
            //disable the form
            $('#OrderForm_OrderForm input').attr('disabled','disabled');
        }
    },
    error: function(data){
        alert('error');
    }
})

Ответ 3

Просмотрите jqXHR Object docs. Вы можете использовать метод сбоя для обнаружения любых ошибок.

Что-то вроде следующего для вашего случая:

$.post(jSONurl+'?orderID='+thisOrderID+'&variationID='+thisVariationID+'&quantity='+thisQuantity+'&callback=?')
.done(function(data){
        if (data.response == 'success'){
            //show the tick. allow the booking to go through
            $('#loadingSML'+thisVariationID).hide();
            $('#tick'+thisVariationID).show();
        }else{
            //show the cross. Do not allow the booking to be made
            $('#loadingSML'+thisVariationID).hide();
            $('#cross'+thisVariationID).hide();
            $('#unableToReserveError').slideDown();
            //disable the form
            $('#OrderForm_OrderForm input').attr('disabled','disabled');
        }
      }, "json")
.fail(function(jqXHR, textStatus, errorThrown){
      alert("Got some error: " + errorThrown);
      });

Я бы также рассмотрел передачу строки json через почту вместо прикрепления переменных запроса:

$.post(jSONurl, $.toJSON({orderID: thisOrderID, variationID: thisVariationID, quantity: thisQuantity, callback: false}))

Ответ 4

Если вы используете POST, вы можете использовать что-то вроде этого:

$.post('account/check-notifications')
    .done(function(data) {
        // success function
    })
    .fail(function(jqXHR){
        if(jqXHR.status==500 || jqXHR.status==0){
            // internal server error or internet connection broke  
        }
    });

Ответ 5

Я удалил dataType: json из вызова ajax, и я смог поймать ошибку. В таких ситуациях мне не нужен контент возвращенного jSON; только для того, чтобы знать, что есть ошибка, возвращаемая, так что этого пока достаточно. Firebug по-прежнему имеет гибкую форму, но я, по крайней мере, способен выполнять некоторые действия, когда есть ошибка

$.ajax({
            url:'http://example.com/jsonservice/LiftieWeb/reserve?token=62e52d30e1aa70831c3f09780e8593f8&orderID='+thisOrderID+'&variationID='+reserveList+'&quantity='+thisQuantity+'&callback=?',
            type: 'POST',
            success: function(data) {
                if (data.response == 'Success'){
                    //show the tick. allow the booking to go through
                    $('#loadingSML'+thisVariationID).hide();
                    $('#tick'+thisVariationID).show();
                }else{
                    //show the cross. Do not allow the booking to be made
                    $('#loadingSML'+thisVariationID).hide();
                    $('#cross'+thisVariationID).hide();
                    $('#unableToReserveError').slideDown();
                    //disable the form
                    $('#OrderForm_OrderForm input').attr('disabled','disabled');
                }
            },
            error: function(data){
                alert('error');
            }
        })