Source:  Twitter logo

I know the problem is usual. I'm using es6 promises, and I have multiple layers. On runtime, when I don't catch a promise, I have Uncaught (in promise) in my console. But the fact is that I do catch it lower in my code.

Fast simplified example :

LoginApi.js

var loginDaoCall = loginDao.login(username, password);

loginDaoCall
    .then(function (res) {
        store.dispatch(loginSuccess());
        log.log("[loginApi.login] END");
    })
    .catch(function (err) {
        store.dispatch(loginFail());
        errorUtils.dispatchErrorWithTimeout(errorLogin);
        log.log(err);
    });

return loginDaoCall;

loginContainer.js

loginApi.login(user, password).then(() => {
    // Change here instead of in render so the user can go back to login page
    this.props.history.push(baseUrlRouter + "test");
}); // <- Error here cause I don't CATCH the promise, but I do catch it in my loginapi.js

I know that I could catch doing nothing, but eh. I could also do the history push thing in my API layer, but it is not its responsibility.

How can I avoid the error in my console? Is there a way? I'm even thinking about leaving it like this.

Your problem is that you were returning the rejected loginDaoCall, not the promise where the error was already handled. loginApi.login(user, password) did indeed return a rejected promise, and even while that was handled in another branch, the promise returned by the further .then() does also get rejected and was not handled.

You might want to do something like

// LoginApi.js
return loginDao.login(username, password).then(function (res) {
    store.dispatch(loginSuccess());
    log.log("[loginApi.login] END");
    return true;
}, function (err) {
    store.dispatch(loginFail());
    errorUtils.dispatchErrorWithTimeout(errorLogin);
    log.log(err);
    return false;
}); // never supposed to reject
// loginContainer.js
loginApi.login(user, password).then(success => {
    if (success) {
        // Change here instead of in render so the user can go back to login page
        this.props.history.push(baseUrlRouter + "test");
    }
});
11 users liked answer #0dislike answer #011
Bergi profile pic
Bergi

It sounds like you have an error in your catch block. When the error is thrown there is no 2nd catch block to catch the error in the 1st catch block.

To fix it ...

.then(function (res) {
    // some code that throws an error
})
.catch(function (err) {
    // some code that throws an error
})
.catch(function (err) {
    // This will fix your error since you are now handling the error thrown by your first catch block
    console.log(err.message)
});
4 users liked answer #1dislike answer #14
danday74 profile pic
danday74

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).