0

How can I achieve, that the caller of saveThings() get's a precise error description (A or B). Currently, my rejection of type A get's caught in the catch() clause, thus the caller always ends up with message B...

saveThings() {
    return api.post(endpoint, data)
    .then( response => {
        if ( !response )
            reject({message: 'error of type A - faulty response'});

        resolve('all went well');
    })
    .catch( err => {
        throw new Error('error of type B - call failed');
    });
}
Frank N
  • 9,625
  • 4
  • 80
  • 110

2 Answers2

3

You'll want to use .then(…, …) instead of .then(…).catch(…):

return api.post(endpoint, data).then(response => {
    if (!response)
        throw {message: 'error of type A - faulty response'};
    return 'all went well';
}, err => {
    throw new Error('error of type B - call failed');
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

well, it depends on when and therefore what you catch

saveThings() {
    return api.post(endpoint, data)
        .catch(err => {
            throw new Error('error of type B - call failed');
        })
        .then( response => {
            if ( !response )
                throw new Error('error of type A - faulty response');

            return 'all went well';
        });
}

or

saveThings() {
    return api.post(endpoint, data)
        .then( response => {
            if ( !response )
                throw new Error('error of type A - faulty response');

            return 'all went well';
        }, err => {
            throw new Error('error of type B - call failed');
        });
}

wich are pretty much equivalent. Only the first one creates an intermediate Promise, after the catch, wich the second one doesn't.

Thomas
  • 11,958
  • 1
  • 14
  • 23
  • Thank you, also to @Bergi. The first solution of turning things around is so simple... too many trees, didn't see the forrest. – Frank N Mar 26 '17 at 14:50