mare
mare

Reputation: 13083

Promise chains don't work as expected

With the code below, my controller's publish() would always go to createCompleted() even if the server returned 500. I was under impression that catch() would be executed when 400 or 500 codes are returned from the server.

// in service

function create(item) {
    return $http
        .post(api, item)
        .then(createCompleted)
        .catch(createFailed);

    function createCompleted(response) {
        return response.data;
    }

    function createFailed(error) {
        $log.error('XHR Failed for create: ' + error.data);
    }
}

// in controller

function publish(item) {

    item.published = true;

    return itemService.create(item)
        .then(createCompleted)
        .catch(createFailed);

    function createCompleted(response) {
        alertService.add('success', 'success.');
        $state.go('^');
    }

    function createFailed(error) {
        alertService.add('error', 'failed');
    }
}

While the controller's createFailed() doesn't hit, the service createFailed() always hits.

What is going on here?

Upvotes: 0

Views: 61

Answers (1)

PSL
PSL

Reputation: 123739

Well that is because you are not propagating the error properly. you would need to throw an exception or reject explicitly from createFailed function.

function createFailed(error) {
    $log.error('XHR Failed for create: ' + error.data);
    throw error;
    // or
    return $q.reject(error); // inject $q
}

So in your case since you are not returning anything it is assumed to be resolved from the returned promise with the value "undefined".

Upvotes: 2

Related Questions