4

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!

CrushedPixel
  • 1,152
  • 2
  • 13
  • 26

1 Answers1

3

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();
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This was just for simplification purposes, I do some more processing with the results of the promise which justifies the "antipattern". – CrushedPixel Feb 02 '17 at 11:31
  • No, there's no justification for the antipattern. Simply do `.then(processing)`, where `processing` is a function that takes the promise results and computes a new return value. Very likely mistakes in the processing were the actual reason why you didn't get any error messages. – Bergi Feb 02 '17 at 12:35
  • They weren't, the issue was in the catch method of the method handling my own promise method. But thanks for your opinion. – CrushedPixel Feb 02 '17 at 13:30