Search code examples
javascriptnode.jspromisetry-catches6-promise

Any problem with catch rejected promise and turn it into resolved with error code?


I am working on a project that always catch rejected promise, turns it into resolved one with error code, like this

return new Promise((resolve, reject) => {
        axios({
          ...
        }).then(res => {
            resolve(res);
        }).catch(err => {
            let res = { ... }
            res.error = err
            resolve(res)
        })
    })

Then whenever call this api, rejected case is handled like this, i.e. without catch

   axios_call(...).then(res => {
        if (!res.err) {
            //resolve case
        } else {
            //reject case
        }
    })

I never handle the rejected promise like this before so I am not sure will it cause any problem or it is just a different code style and works fine too.

I checked the possible duplicated q/a What is the explicit promise construction antipattern and how do I avoid it? But I believed they are not the same. Because my question is about handling the rejected promise while that question is about deferred object, e.g. errors and rejections are not swallowed in my case.


Solution

  • First of all, avoid the Promise constructor antipattern! Your axios_call code should better look simply like this:

    return axios({
        ...
    }).catch(err => {
        return { ..., error: err };
    });
    

    Then whenever call this api, rejected case is handled without catch. I never had handled the rejected promise like this before so I am not sure will it cause any problem or it is just a different code style and works fine too.

    It works, but it's not fine. This style of error handling is weird and really non-idiomatic. It has the same problems as the traditional node-style callback API with separate error and result parameters:

    • the promise can't know whether you handled the error or not. You will not get any unhandled rejection warnings.
    • you always must write the code to deal with the res.error, if you want it or not. With normal promise usage, you could just supply separate onFulfill and onReject callbacks, and omitting the latter will get you the sensible default behaviour of forwarding the error instead of just dropping it.

    I cannot see any advantages that your style would present, so I would recommend to avoid it and use normal promise rejections.