Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

64
Views
How to declare custom props to RequestHandler in express js middleware functions?

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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!