0

I have a function that does ajax calls, another one that handles errors. The target is: Manipulate the error into a better format to use later (see example below).

The problem: The second callback for .then() isn't called though.

The code:

function _handleError(error) {
    //bring error info in better usable format
    ...

    return errorRes;
}

function getSth(...) {
    ...
    return $.ajax({
        url: baseUrl + query,
        type: "GET",
        headers: {
           ...
        }
    }).then(function (data) {
        var results = data.d.results;

        ... //Do mapping stuff

        return results;
    }, _handleError);
}

How I would like to implement it:

getSth(...).then(function(results){
    ...
}, function(err){
    console.log(err);
    ... //Do more with error info
});

The second function given to .then() never gets called, _handleError() is though. I'm quite sure I misunderstood something on Promise concepts.

sandrooco
  • 8,016
  • 9
  • 48
  • 86

1 Answers1

1

If, after _handleError is called, you want the promise chain to continue as rejected, then you need to either throw or return a rejected promise from within _handleError.

If you return nothing or just return a normal value from handleError, then the Promise infrastructure assumes that you "handled" the error and it is no longer an error. This is modeled after try/catch where if you catch an error and do not rethrow, then the exception is considered handled and does not propagate to a higher level.

Example:

function _handleError(err) {
    // do something to the error value
    let newError = new Error(...);

    // rethrow the error so the promise continues as rejected
    // and so that the next error handler on that promise chain will get called
    throw newError;
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979