Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http.get call error function from success

I do not have the ability to change an endpoint, and it will return a 200 OK response with different data if it fails. How can I make it run the error function (The 2nd function in a then from a promise)?

MyService service:

self.getData = function() {
    return $http.get('/api/controller/action').then(function(x) {
            //This will be run even on failure. How can I call....
            return x.data;
        }, function(x) {
            //......here, from the front-end, so that, the 2nd function in
            //inside the 'then' in the controller is run.
            //This code will currently never run as it never fails server side.
            return x;
        });
};

controller:

MyService.getData().then(function(x) {
    //Success
}, function(x) {
    //Failure
});
like image 538
tic Avatar asked Mar 12 '23 08:03

tic


1 Answers

Use $q.reject, eg

return $http.get('/api/controller/action').then(function(x) {
    if (x.data === 'some error condition') {
        return $q.reject(x);
    }
like image 192
Phil Avatar answered Mar 19 '23 11:03

Phil