CrushedPixel CrushedPixel - 4 years ago 119
Javascript Question

NodeJS: Auto-catch errors in Promise and call reject

I recently found myself in a situation very difficult to debug.
Imagine the following very simple situation:

function somePromise() {
return new Promise((resolve, reject) => {
SomeModule.someMethod();
AnotherModule.somePromise().then(resolve).catch(reject);
});
}


Resolve was never called, but I didn't get an error in the console - this was difficult to debug!

Turns out that I forgot to require
SomeModule
. After requiring it, the code worked as expected.

Is there a way to automatically try/catch every Promise in my code with an error handler? I don't want to surround the body of my Promises with a try/catch block just to be able to find such errors more easily in the future.

Thanks in advance for opinions!

Answer Source

Is there a way to automatically try/catch every Promise in my code with an error handler?

This is implicitly done by the Promise constructor already. If the callback throws an exception synchronously, the promise will reject.

However, you really should avoid the Promise constructor antipattern! Use

function somePromise() {
    SomeModule.someMethod();
    return AnotherModule.somePromise();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download