0

I cannot find a way to catch, at the top level, exceptions that might occur deep in a promise fulfillment chain. Here is the sample code that I've written and two different approaches, neither of which works:

import * as Q from 'q';

function main()
   {
   console.log("In main now.");
   One().then(function()
      {
      console.log("One's promise fulfilled.");
      })
   .catch(function()
      {
      console.log("One's promise rejected.");
      })
   }

function One() : Q.Promise<void>
   {
   var deferred = Q.defer<void>();
   Two().then(function()
      {
      console.log("Two's promise fulfilled.");
      this.foo();
      deferred.resolve();
      })
   return deferred.promise;
   }

function Two() : Q.Promise<void>
   {
   var deferred = Q.defer<void>();
   deferred.resolve();
   return deferred.promise;
   }

main();

The alternative I've tried is to use an onReject handler like so:

function main()
   {
   console.log("In main now.");
   One().then(function()
      {
      console.log("One's promise fulfilled.");
      },
   function()
      {
      console.log("One's promise rejected.");
      })
   }

In neither approach am I able to catch the exception that occurs at line:

this.foo();

In other words, neither approach generates the "One's promise rejected" output to the console. Is there any way to catch such exceptions at the top level?

  • 1
    The problem is not with your attempt at error handling, it's with the implementation of `One`. Don't use deferreds for this! Just `return Two().then(function() { console.log("Two's promise fulfilled."); this.foo(); })` – Bergi Jun 01 '17 at 23:44
  • Thank you @Bergi. I think I now understand the error of my ways. However, suppose I don't have control over the entire stack? Suppose I rewrite One correctly but now we add Three which is called by Two and suppose that Two is implemented INcorrectly as per my initial implementation of One. Then it appears that nothing I do at the top level can help to catch this. – Charles Moore Jun 02 '17 at 00:11
  • Yes, if some function does ignore errors and just never settles the returned promise, there's nothing you can do as a caller (except maybe for a timeout). – Bergi Jun 02 '17 at 01:06

0 Answers0