title: Error handling when throw an error for user authentication nodejs
body: <p>I have set up a middleware for error handling:</p>
  <pre><code>//errorMiddleware.js
  export const notFound = (req, res, next) =&gt; {
    const error = new Error(`Not Found - ${req.originalUrl}`);
    res.status(404);
    next(error);
  };
  
  export const errorHandler = (err, req, res, next) =&gt; {
    res.status(err.status || 500);
  
    res.json({
      errors: { message: err.message },
    });
  };
  </code></pre>
  <p>I try to write API to auth user, for example. When user enter wrong email or password, I throw an error:</p>
  <pre><code>const { email, password } = req.body;
  
    const user = await User.findOne({ email });
  
    if (user &amp;&amp; (await user.comparePassword(password))) {
      res.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        isAdmin: user.isAdmin,
        token: generateToken(user._id),
      });
    } else {
      res.status(401);
      throw new Error(&quot;Invalid email or password&quot;);
    }
  </code></pre>
  <p>However, I use postman to test request, it's cause an error and not send any response i have set up above:</p>
  <pre><code>(node:15900) UnhandledPromiseRejectionWarning: Error: Invalid email or password
      at authUser (file:///D:/Practice%20Web/MERN/eCommerce/backend/controllers/userController.js:20:11)       
      at processTicksAndRejections (internal/process/task_queues.js:95:5)
  (Use `node --trace-warnings ...` to show where the warning was created)
  (node:15900) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)        
  (node:15900) [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.
  </code></pre>
  <p>How can I handle that problem. Thanks in advance!</p>