$ http.get call error function from success

I have no way to change the endpoint, and it will return a 200 OK response with different data if it does not work. How to make error function run (second function in thenfrom 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
});
+4
source share
2 answers

Use $q.rejectfor example

return $http.get('/api/controller/action').then(function(x) {
    if (x.data === 'some error condition') {
        return $q.reject(x);
    }
+7
source

you can also check the status of the response that you get after getting into the API, for example, means that there is some problem in the API

if (state! = 200) {

// do something

}

0
source

Source: https://habr.com/ru/post/1652131/


All Articles