Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
How is this an unhandled promise rejection inside a try catch block?
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(401).json("Invalid credentials!");

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );

    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
    originalPassword !== req.body.password &&
      res.status(401).json("Invalid credentials!");

    const { password, ...others } = user._doc;

    res.status(200).json(others);
  } catch (error) {
    res.status(500).json(error.message);
  }
});

When I post an incorrect username or an incorrect password I do get the correct HTTP Response Invalid Credentials!

However I receive an unhandled promise rejection error in my console log.

(node:12080) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:267:15) at C:\Users\dinin\Projects\testexpress2\routes\auth.js:24:21 at processTicksAndRejections (internal/process/task_queues.js:95:5) (node:12080) 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: 4)

It's obviously in a try catch block. How can I "handle" this promise properly?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!