0

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?

PSL
  • 123,204
  • 21
  • 253
  • 243
mare
  • 13,033
  • 24
  • 102
  • 191
  • 1
    possible duplicate of http://stackoverflow.com/q/25372160/1048572. See also [these control flow diagrams](http://stackoverflow.com/a/24663315/1048572) and http://stackoverflow.com/q/26076511/1048572 – Bergi Feb 05 '15 at 22:02

1 Answers1

2

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".

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
PSL
  • 123,204
  • 21
  • 253
  • 243
  • What if I used $http's success and error methods on it's promise (rather than then() and catch()) would that be better somehow? – mare Feb 05 '15 at 21:44
  • @mare no, the issue wouldis that `$http(args)` return httpPromise and $http(args).then.. returns q promise. But yes if you return $http you will get both error blocks executed. But then if you want to chanin through transforming and propagating data you would want to do `then` instead of success. – PSL Feb 05 '15 at 21:53