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

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?

Author: Fantashit

1 thought on “How to bypass middleware callbacks and pass control to last callback in a route?

  1. 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.

Comments are closed.