Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to bypass middleware callbacks and pass control to last callback in a route? #1662

Closed
justin-john opened this issue Jun 27, 2013 · 2 comments

Comments

@justin-john
Copy link

I have three middleware callbacks in a route. I want to bypass middleware callbacks and pass control to last callback.

A example code

var middleware = [loadData, loadForum, loadThread];

app.get('/forum/:fid/thread/:tid', middleware, finalMethod);

Use case: If first callback loadData enters into strange case like failing to load data. I would like by pass loadForum and loadThread middleware callbacks and pass control to last route callback finalMethod.

If next() is called in middleware callback, it will go to next callback.
If I understand correctly, next('route') will go to other route given in argument of next method, not to last route callback.

How to bypass middleware callbacks and pass control to last callback?

I am trying to avoid deep nested functions in methods. So I think to set middleware in routes, each nesting functions can be splitted into each method and setting it's result in request object. So that next middleware method can be access its result through request object.
Is this good way to handle deep nested functions or any other good way to do this?

@MarcDiethelm
Copy link

Call next(err) in loadData, errbeing either an error you receive while loading the data or an error you create.

Any middleware that has a length of 4 (4 arguments) is considered error middleware. When one calls next(err) connect goes and calls error middleware.

Define a (global) error middleware like so:

app.use(function(err, req, res, next) {
    // todo: test if this is the loadData error.
    // todo: if it is, call your last middleware directly.
    // todo: else next(err);
});

Or you, as you mentioned yourself, you can set a property on req and test for it in subsequent middlewares.

@tj
Copy link
Member

tj commented Aug 11, 2013

there's no built-in way to skip to the final route callback, you'd have to add checks for something like if (req.skip) return next() etc

@tj tj closed this as completed Aug 11, 2013
@expressjs expressjs locked and limited conversation to collaborators Oct 23, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants