Home > Net >  How to declare custom props to RequestHandler in express js middleware functions?
How to declare custom props to RequestHandler in express js middleware functions?

Time:08-06

I have an error handling middleware which handles the errors in my express app like this :


export const errorMiddleware = (app: Application): void => {
  // If the route is not correct
  app.use(((req, res, next): void => {
    const error: any = new Error("Route not found");
    error.status = 404;
    next(error);
    logger.error(`${error.status} ${error.message}`);
  }) as RequestHandler);
  // If any operation fail and throw error with next will come here
  app.use(((error, req, res, next): void => {
    logger.error(`${error.status} ${error.message}`);
    res.status(error.status || 500).json({
      error: {
        message: error.message,
      },
      status: error.status || 500,
    });
  }) as RequestHandler);
};

The first app.use passes an error object to the next middleware which gets that error object in the first parameter :

 app.use(((error, req, res, next): void => {

Now I've declared a RequestHandler type for it and it gives error because of that custom first parameter it gets which is error .

enter image description here

How can I use the RequestHandler prop with one extra prop type added to it so I can fix this error ?

CodePudding user response:

You can not introduce new parameters in a callback function like that, it just accepts fixed parameters and in that order. So your error parameter will contain req!

To pass data from one middleware to the next middlewares, use res.locals.

Take a look at http://expressjs.com/en/api.html#res.locals

You should set it in your first middleware like this:

res.locals.error = 'Sorry'

And you can use it in the next middlewares like this:

if (res.locals.err) {...}

It's persisted in the request's lifecycle.

  • Related