title: How to throw an error inside the pre handler in Hapi.js
body: <p>I started using <code>v17</code> of <code>Hapi.js</code> and I am running into issues when using the pre-handler. </p>
  
  <p>I want to save a user into a database, but first I use the pre-handler to check if a user already exists. If the user exists, I want to throw an error. The structure of my route is as so...</p>
  
  <pre><code>module.exports = {
      method: "POST",
      path: "/users",
      config: {
          auth: false,
          pre: [{ method: verify_unique_user}],
          handler: create_user.create
      }
  }
  </code></pre>
  
  <p>The content of <code>verify_unique_user</code> is...</p>
  
  <pre><code>async function verify_unique_user(req, h) {
  
      await User.findOne({
          $or: [{email: req.payload.email}, {username: req.payload.username}]
      },
      (err, user) =&gt; {
  
          if (user) {
  
              // Check if username exists.
              if (user.username === req.payload.username) {
                  throw Boom.badRequest("Username taken!");
              }
  
              // Check if email exists.
              if (user.email === req.payload.email) {
                  throw Boom.badRequest("Email taken!");
              }
          }
  
      });
  
      return req;
  }
  </code></pre>
  
  <p>Let's assume the user already exists in the database. Then an error will be thrown from either of the <code>if</code> statements. When this happens, I get the following error...</p>
  
  <blockquote>
    <p>events.js:167</p>
  
  <pre><code> throw er; // Unhandled 'error' event
  
   ^
  </code></pre>
    
    <p>Error: Username taken!
        at User.findOne (/Users/ericbolboa/Desktop/Warble/server/src/users/util/user_function.js:16:16)</p>
  </blockquote>
  
  <p>This crashed my server. This is not what I want. If I throw an error in my handler function, the response looks like this...</p>
  
  <pre><code>{
      "statusCode": 400,
      "error": "Bad Request",
      "message": "error"
  }
  </code></pre>
  
  <p>But whenever I throw an error in the pre-handler, my server crashes. How can I throw errors properly?</p>