0

Simplified code:

// File A

module.exports = new Promise((res, rej) => {

  ... do stuff

  if (someErr) {
   return rej(someErr);
  }

  return res(stuff)
}

// File B

const fileA = require('./fileA');

... express stuff

app.get('/getA', (req, res) => {
  fileA
    .then(data => res.send(data))
    .catch(e => res.send(404, e));
  });

As you can see the promise rejection gets caught when running a post request to a route in file B. This way it is also possible to send a 404 response with the original error trough.

The problem is, there is an Unhandled Promise Rejection from file A whenever the route is called. VERY annoying.

(node:5040) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

(node:5040) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Yes, sure, i could catch the rejection in file A, but i would rather prefer it propagate upstream and catch it later.

Community
  • 1
  • 1
Rastur
  • 137
  • 1
  • 3
  • 12
  • Just do `fileA.catch(err => console.debug("A will not be available (404) because "+err));` in the second file to handle the rejection immediately. You can still chain other handlers to the promise for answering requests. If you don't want a log message, write `fileA.catch(err => { /* ignore */ });` (with a comment about where it will be handled later). – Bergi Nov 24 '18 at 14:37

1 Answers1

0

With the way you structured your code, the rejection is thrown before the .catch is attached to the promise, so technically, it's was unhandled at the moment it was thrown.

I'm sure you have a reason why you would want to structure it like that (perhaps run "do stuff" only once?), so a possible workaround would be this:

// File A
let promise = null;
module.exports = () => {
  if (! promise) {
    promise = new Promise((res, rej) => {

      ... do stuff

      if (someErr) {
        return rej(someErr);
      }

      return res(stuff)
    });
  }
  return promise;
};

// File B
app.get('/getA', (req, res) => {
  fileA()
    .then(data => res.send(data))
    .catch(e => res.send(404, e));
});
robertklep
  • 198,204
  • 35
  • 394
  • 381