Saturday 6 May 2017

Unhandled promise rejection on redirect in Nodejs

I have stumbled upon a strange issue with promises when redirecting in nodejs. In the code below I am using a function to handle writing to an object which will check if the item exists if it does it rejects, if it does not it resolves. When it resolves I am then redirecting the user to another page which contains the id used in the example in its url.

var Test = function() {

  var obj = {};

  function addItemToObj(id) {
    return new Promise(function(resolve, reject) {

      var idAlreadyExists = obj[id] ? true : false;

      if (idAlreadyExists) {
        return reject('id already exists');
      }

      obj[id] = 'test';
      return resolve(id);
    });
  }

  return {
    createTestPage: function(request, response) {

      var id = 'testid';

      return addItemToObj(id).then(function(id) {
        return response.redirect(`/newPage/${id}`);
      }).catch(function(error) {
        console.error(error);
      });
    }
  }
}

module.exports = new Test;

So when I run this code I get this error:

(node:46878) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot create property '_locals' on string 'Model already exists'

The error is saying that I am not handling the rejection, but I am in the catch. When I remove the redirect the error goes away, but I cannot find out why.

Can anyone shed any light on this issue?



via mmacartney

No comments:

Post a Comment