Search code examples
javascriptecmascript-6promisees6-promise

ES6 Promises return before catch


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');
    });
}

Solution

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