0

I have a function main which contains a promise but does not return one. Something like this.

function main() {
  var prom = new Promise(function(resolve, reject) {
    setTimeout(() => {
      console.log("testing");
      reject();
    }, 2000);
  });

  return "success";
}

main();

When I run the code, it gives an Uncaught (in promise) DOMException and stops the javascript code. I can't modify the main function at all. How can I catch the rejection?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
pransin
  • 15
  • 4
  • wrap main() execution in try/catch – Nonik Jun 16 '22 at 18:28
  • 1
    @Nonik that won't help because promise is rejected _asynchronously_. Wrapping `main()` in `try-catch` will only catch errors thrown _synchronously_ inside the `main` function. – Yousaf Jun 16 '22 at 18:31
  • have a look at this: https://stackoverflow.com/a/24979785/18472980 – Dheeraj Sharma Jun 16 '22 at 18:41
  • Does this answer your question? [Catching Errors in JavaScript Promises with a First Level try ... catch](https://stackoverflow.com/questions/24977516/catching-errors-in-javascript-promises-with-a-first-level-try-catch) – ggorlen Jun 16 '22 at 18:45

1 Answers1

3

You can listen for the "unhandledrejection" event.

window.addEventListener("unhandledrejection", e => {
    e.preventDefault(); // prevent error message
    // handle...
    // e.promise is the Promise that was rejected
    // e.reason is the object passed to reject()
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80