0

I have a simple Promise that I execute:

function handleCall(url) {
    return new Promise((resolve, reject) => {
        xhr.get(url).then(
            resolve,
            err => {
                if (!reject(err)) {
                    // Handle here the error in a generic way
                }
            }
        )
    }
)

The idea here is to let me handle the error when I want, by adding a .catch to the handleCall method, but if there is no catch mechanism, the handleCall would fall back to the default actions defined in that function.

Of course, my above code doesn't work, the reject function returns null even if my custom catch returns something.

I tried with a try/catch block instead, in the idea that "if no catch method is defined when calling, then an exception might be thrown", but it's not working either.

Is there a way to achieve this? I mean, letting the caller of handleCall handle the error, but if no error has been implemented (no catch), then fallback to the generic one on handleCall?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
  • 3
    [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) – VLAZ Aug 12 '21 at 08:51
  • You can't know that. The consumer calling `.then` and/or `.catch` on your promise is creating _new_ promises, based on the source. You might as well just `return xhr.get(url);` and not create the `new Promise` at all. – jonrsharpe Aug 12 '21 at 08:54

0 Answers0