SergeyK SergeyK - 3 months ago 21
TypeScript Question

typescript promise rejecting and vscode debugger behavior

I'm trying to learn promises, with typescript, and i have some problems, understanding what causes such vscode debugging behavior.

Here is an examples:

// example 1
new Promise((resolve, reject) => {
reject("test1"); // debugger stops as on uncaught exception
})
.catch(
error => {
console.log(error);
}
);
// output: "test1"


,and:

//example 2
new Promise((resolve, reject) => {
setTimeout(() => {
reject("test2"); // debugger never stops
});
})
.catch(
error => {
console.log(error);
}
);
// output: "test2"


As you can see in one case debugger stops at promise reject, but in other case, not. But in all cases error is catched, and no unhandled exceptions.

Is it vscode specific behavior or maybe es6-promise binding that i use? Or i'm doing it incorrect way? Has anyone faced same problem?

Answer

This is a heuristic that the Chrome debugger which VSCode hooks into uses. They assume that synchronous rejections are typically programmer errors you want to break on (like a typo) and asynchronous ones are not since they're typically IO (reading a file).

It's a pretty dumb heuristic but it typically makes sense for some cases. One thing you can do is include bluebird for the debug build (it's 100% compliant if you don't subclass Promise) and then add an unhandled rejection hook:

Promise.onPossiblyUnhandledRejection(function(e, promise) {
    throw e;
});

Which uses a much nicer heuristic. You can also do this with native promises (with rejection events) but I don't know how you can turn off the automatic breaking on synchronous throws.