3

In my Controller:

function login(credentials) {
  AuthService
    .login(credentials)
    .then(successCallback, errorCallback);
    //same issue with .then(successCallback).catch(errorCallback);
}

function successCallback() {
  // do something after success
}

function errorCallback(data) {
  // do something after error
}

and in my AuthService:

authService.login = function (credentials) {
  return $http
    .post(ENV.apiEndpoint + 'api/v1/login_check', credentials)
    .then(
       function (result) {
        Session.create(result.data.token, result.data.data);
       },
       function (data) {
        Messages.create('Login failed: ' + data.statusText);
       }
    );
}

When my POST delivers a 200 response code, everything works as expected do something after success is executed.

But when my POST results e.g. in a 401 I can see that Messages.create is called (so in this case it enters the error path), but unfortunately my Controller calls the successCallback and not the errorCallback.

I had to migrate this because I was using the deprecated and since Angular 1.6 removed .success and .error promise attributes. It was working back then, but after migration this doesn't work anymore.

What am I doing wrong here?

2
  • you'll need to throw from the Messages.create('Login failed: ' + data.statusText); block Commented Feb 22, 2017 at 12:58
  • 1
    angulra doesn't like throwing, return $q.reject() is better Commented Feb 22, 2017 at 12:59

1 Answer 1

6

You may reject the promise in your error callback.

authService.login = function (credentials) {
  return $http
    .post(ENV.apiEndpoint + 'api/v1/login_check', credentials)
    .then(
       function (result) {
         Session.create(result.data.token, result.data.data);
       },
       function (data) {
         Messages.create('Login failed: ' + data.statusText);
         return $q.reject(data);
       }
    );
}

From Angular $q doc:

reject(reason);

Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.

When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.