title: Using rejected promises to handle bad HTTP calls?
body: <p>So, I have the following code:</p>
  
  <pre><code>function SignUp(req, res, next){
  
      const userCreds = {
          email: req.body.email,
          password: req.body.password
      }
  
      //Username and password must exist
      if(!userCreds.email || !userCreds.password){
          res.status(422).send({ error: 'Email and Password required'});
          throw new Error(('Email and Password Required'));
      }
  
      //See if email is already being used
      Users.findOne({ email: userCreds.email })
      .then(function(user){
          //If user does exist, return Error
          if(user){
              res.status(422).send({ error: 'Email is in use'});
              throw new Error(('Email and Password Required'));
          }
  
          //Else if email is true, create and save user error
          const newUser = new Users(userCreds);
  
          //Save the user
          return newUser.save(); //Return promise
      })
      .then(function(doc){
          //Respond saying all OK
          res.json({
              success: true,
              email: doc.email
          });
      })
      .catch(function(err){
          if(err)
              return next(err);
      });
  }
  </code></pre>
  
  <p>The function above is passed to an Express route, like this 
  <code>app.get('/signup', SignUp);</code></p>
  
  <p>In this code, there are two different 'errors' that can occur and I need to handle. One kind of error is that the user request cannot be processed (Trying to create an account without supplying both Email and Password, or using an Email that already is being used). The second kind of error is one that I have less control in: rejected promises from the Mongoose package. </p>
  
  <p>Let's say that I have received a bad request, an error of type 1. I want to handle it by setting the header of the response to 422, and sending that response with a message detailing why it could not be processed. At that point the execution would end.</p>
  
  <p>If I get an error of type 2, I want to call <code>next(error)</code> and stop execution at that point.</p>
  
  <p>The problem is, by chaining <code>.then()</code> functions, I cannot <code>return</code> from a block of code without jumping into the following <code>.next()</code>. </p>
  
  <p>One way to get around this is by throwing an error via <code>throw new Error()</code> when I get an error of either type 1 or 2, and handle the case in <code>.catch()</code>, but I am unsure how much of a good or bad practice this would be.</p>
  
  <p>How can I make it so that I can handle the error in a <code>.then()</code> block and then stop execution? And would that be the best way to do it? </p>
  
  <p>Is there a better way to handle these kind of situations in Express? Am I missing anything? </p>
  
  <p>Thank you!</p>