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

316
May 01, 2017, at 07:32 AM

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?

READ ALSO
Mongoose: Exclude objects from results based on another model

Mongoose: Exclude objects from results based on another model

Let's say I have a User and Group model, groups have users, like

423
What to use in NodeJS to create process which works long time and is accessible during its lifetime

What to use in NodeJS to create process which works long time and is accessible during its lifetime

I want to create some process which will work for a long time and it will be possible to obtain data from this process by get request

282
Routing in ReactJS

Routing in ReactJS

Can anyone explain to me how Routing works in Reactjs?

469