How to trigger jquery.ajax() error callback based on server response, not HTTP 500?

后端 未结 6 1121
清酒与你
清酒与你 2020-11-30 03:32

By using jquery ajax function, I can do something like:

$.ajax({

  url: url,
  type: \'GET\',
  async: true,
  dataType: \'json\',
  data: data,

 success:          


        
相关标签:
6条回答
  • 2020-11-30 04:06

    This original question was posted years ago, and perhaps there are better ways of handling this now. Here's a suggestion to handle multiple types of errors, including the OP's question.

    Input type (error) example #1

    function handleError (type){
    type = type || "Connection Issue";
     var value = "Error occurred: " + type;
     alert(value);
    }
    
    function checkIfError(response){
        if (response == "DB_ERROR") {
            handleError("Server error");
            throw new Error("JS died"); // optional, keep from running additional script
         }
    }
    
    var example = {
    
        success: function (response) {
            checkIfError(response); // check data if error msg
            // do stuff when proper data sent
            alert(response);
    
        }, error: handleError // connection error, call error msg
    };
    
    test1 = example['error']();

    Input type (success:error) example #2

    function handleError (type){
    type = type || "Connection Issue";
     var value = "Error occurred: " + type;
     alert(value);
    }
    
    function checkIfError(response){
        if (response == "DB_ERROR") {
            handleError("Server error");
            throw new Error("JS died"); // optional, keep from running additional script
         }
    }
    
    var example = {
    
        success: function (response) {
            checkIfError(response); // check data if error msg
            // do stuff when proper data sent
            alert(response);
    
        }, error: handleError // connection error, call error msg
    };
    
    
    test2 = example['success']("DB_ERROR");

    Input type (success) example #3

    function handleError (type){
    type = type || "Connection Issue";
     var value = "Error occurred: " + type;
     alert(value);
    }
    
    function checkIfError(response){
        if (response == "DB_ERROR") {
            handleError("Server error");
            throw new Error("JS died"); // optional, keep from running additional script
         }
    }
    
    var example = {
    
        success: function (response) {
            checkIfError(response); // check data if error msg
            // do stuff when proper data sent
            alert(response);
    
        }, error: handleError // connection error, call error msg
    };
    
    
    test3 = example['success']("Proper Response");

    By using functions, if you have multiple calls in your scripts, you can simplify changes.

    Have your PHP (or whatever server side code) return the response of "DB_ERROR" (or whatever you want) to trigger the error; allows you to do different things depending on the error.

    0 讨论(0)
  • 2020-11-30 04:14

    The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

    • HTTP 404/500 or any other HTTP error message has been received
    • data of incorrect type was received (i.e. you have expected JSON, you have received something else).

    In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.

    function handleError(xhr, status, error){
    
        //Handle failure here
    
     }
    
    $.ajax({
    
      url: url,
      type: 'GET',
      async: true,
      dataType: 'json',
      data: data,
    
     success: function(data) {
         if (whatever) {
             handleError(xhr, status, ''); // manually trigger callback
         }
         //Handle server response here
    
      },
    
     error: handleError
    });
    
    0 讨论(0)
  • 2020-11-30 04:15

    We presume the server is sending JSON, and in case of a successful request we'll get something like this:

    {
        success: true,
        data: {
            name: 'Foo'
        }
    }
    

    ... and on failure:

    {
        success: false,
        error: 'Something bad happened.'
    }
    

    Then we simply filter the response with a $.Deferred:

    $.get('http://localhost/api').then(function(res) {
        var filter = $.Deferred();
    
        if (res.success) {
            filter.resolve(res.data);
        } else {
            filter.reject(res.error);
        }
    
        return filter.promise();
    }).done(function(data) {
        console.log('Name:',  data.name); // Outputs: Foo
    }).fail(function(error) {
        console.log('Error:', error); // Outputs: Something bad happened.
    })
    
    0 讨论(0)
  • 2020-11-30 04:17

    The error callback is for when the Ajax round-trip could not be completed successfully, not something based on your server logic. It would be your responsibility to check for what you consider to be a successful response inside the success callback. i.e. Add a single IF conditional that checks if the message = "There was an error." and include your error logic there, otherwise do the success logic.

    An approach to do what you ask for would be to have the server return a 404 header when there is an error, then it would be handled by the error callback. The problem with this approach is that you'd be hiding if there are actual errors, and you wouldn't be able to pass additional data with it.

    0 讨论(0)
  • 2020-11-30 04:25

    One easy way to do this is to just use the jQuery always() function for your callback and then if you want to manually create an error just take advantage of Duck Typing!

    For example:

    $.get(url, {"data": data}).always(function(result)
    {
        if (typeof result.status !== "undefined" && result.status !== 200) // Status code 200 represents Success/OK
        {
            //handle error
            error = "Your error was " + result.status + " " + result.statusText;
        }
        else
        {
            //success
        }
    });
    

    The error section will always be run if there was a natural header error such as a 404 Not Found. If you want to manually return an error, you can just emulate the XHR object normally passed with an error (e.g. in PHP):

    public function ServerSideAjaxResponse($data)
    {
        if (!$data)
        {
            $response["status"] = 1001; //Make up your own error codes! Yippee! Fun!
            $response["statusText"] = "Error! You forgot to send the data!";
            echo json_encode($return);
            return;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:28

    Simplest thing to do would be to restructure like so:

    function handleAjaxError function(xhr, status, error) {
        //Handle failure here
    }
    
    $.ajax({
      url: url,
      type: 'GET',
      async: true,
      dataType: 'json',
      data: data,
    
      success: function(data) {
    
         //Handle server response here
        if (data.message == 'There is an error')
        {
            handleAjaxError();
            return;
        }
    
        //... all is good....
    
      },
      error: handleAjaxError
    });
    
    0 讨论(0)
提交回复
热议问题