Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop middleware chain?

How can I properly end a middleware chain in case of error ?

In my code I have

    if (someProblem) {
        res.status(statuscode).json({message: 'oops'});
        return;
    }

Yet the midleware in the chain after that keeps getting called giving me the Can't set headers after they are senterror.

like image 610
Lev Avatar asked Dec 02 '16 00:12

Lev


People also ask

How many middleware can be on a single route?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.

What does next () do in Express?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

What is middleware in Javascript?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc.


2 Answers

Middleware does not advance on its own. It only goes to the next step in the chain when you call next() so as long as you don't call next(), then the next step will not execute.

So, if you just send a response and return (without calling next()), then you should not have an issue.

The code you show in your question would not, all by itself, cause the error message you refer to so there must be more going on that you aren't showing us for that error to occur.

like image 80
jfriend00 Avatar answered Oct 06 '22 06:10

jfriend00


So you simply have to attach an errorHandler (which is a function that takes 4 parameters) before you create the actual server instance.

Anywhere in the app you can now simply create an error with var newError = new Error('my error message'); and pass it to the next callback with next(newError); To stop the execution after the error has been thrown and to not send a response twice use return next (newError);

// example route
app.get('/test', function(req, res, next){
  if (someProblem) {
    var newError = new Error('oops');
    return next(newError);
  }
  res.send('all OK - no errors');
});

// attach this errorHandler just before you create the server
app.use(function(error, req, res, next){
  console.log(error);
  res.status(500).json(error);
});

// this is where you create the server
var server = app.listen(4000, function(){
 console.log('server started');
});
like image 2
Ludwig Goohsen Avatar answered Oct 06 '22 07:10

Ludwig Goohsen