Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop function after next() in node.js?

Ok, I have code like this:

app.get('/someUrl', function(req, res, next){
    if(req.body.username==''){
        next({'type':'error', 'httpCode':400, 'message': {'errCode': 'e402', 'text': 'Not name specified'}})
    }

    var user=new User({'name':'Jack Leeeee'})
    user.save(function(err, affected) {
        if (err) next({'type': 'error', 'httpCode': 400, 'message': {'errCode': 'e403', 'text': 'Bad error :('}})
        console.log('all is ok!')
        res.send(200, "Ok")
    })
})

When I try to send empty request, my error handler send to me right response by next() function. But after this user schema trying to save(that makes exception). How I can stop app.get() function after calling next()?

Only way, that I found is call

return false;

after next(), but this method didn't work in async functions(like user.save()), it's obviously

UPD1: In another word, how to avoid 'Still alive' in console?

user.save(function(err,c){
    return next(err)
})
console.log('Still alive')
like image 739
user3922749 Avatar asked Jan 11 '23 01:01

user3922749


2 Answers

Either you want node+express's asynchronous next() behaviour, or you need to cut it off explicitly:

var middleware = {
  auth: function(req, res, next) {
    if(req.body.username=='') {
     return next({
       'type':'error',
       'httpCode':400,
       'message': {
         'errCode': 'e402',
         'text': 'Not name specified'
       }
     });
    }
    next();
  }
}

var routes = {
  someurl: function(req, res) {
    console.log('all is ok!')
    res.send(200, "Ok")
  }
}

app.use(function universalErrorHandler(req, res, next, err) {
  console.error("oh no something went wrong!");
  console.error(err);
});


app.get('/someUrl', middleware.auth, routes.someurl);

The idea is you do every "step" in its own function. Should processing continue? call next() without an error argument. Should processing be aborted? call next() with an error argument. When express sees a next(err) being called, it'll send it over to the global error handler if there is one, or throw an exception if you didn't define one.

Notice that your code has been split up into three parts: a middleware object for handling "in the middle" checks, a routing object for generating the final data that should come back from URL requests, and an app.get for a route that has one middleware step, and one final content generating function.

The idea with express is to do as little as possible per step. Need to verify four parameters? That's four middleware functions, and then called as app.get("someroute", fn1, fn2, fn3, fn4, generatePage), with each middleware function either calling next() on success, or next(new Error(...}); when something went wrong.

like image 149
Mike 'Pomax' Kamermans Avatar answered Jan 16 '23 22:01

Mike 'Pomax' Kamermans


Like it was said in the comments

return next(err)

should solve your problems.

like image 44
Olu Avatar answered Jan 16 '23 22:01

Olu