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

264
Views
Express.js throw exception and return pre-defined status code

In spring i use define my own class extending Exception annotate it with @ResponseStatus to throw it in specific situation to return to user specific status code and error message. I'd like to do something similar in Express.js in Node.js. Is it possible?

Now I use Q to return rejected promise from loginService and return explicitly response code and message.

router.post('/log-in', jsonParser, (req, res) => {
  loginService.authenticate(req.body.userLogin, req.body.userPassword)
    .then((successLogin)=>{
    res.json(successLogin);
    }, function (error) {
      res.status(error.code).json({message: error.reason});
    })
});

but my goal is to handle only resolved promises and throw whenever an error occurred. something like

router.post('/log-in', jsonParser, (req, res) => {
  loginService.authenticate(req.body.userLogin, req.body.userPassword)
    .then((successLogin)=>{
    res.json(successLogin);
    })
});

and I imagine service throwing like

if(!user) new Error(404, 'Cannot find user')

and response returned to user would have desired code and message. Is it possible to implement it in Node? Would it be efficient?

about 4 years ago · Santiago Trujillo
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!