Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

273
Vistas
How does this function that takes in a RequestHandler in express work?

I was browsing through some code examples for Express server on GitHub and came across this function used to wrap around REST API controllers and was confused how it works...

import { RequestHandler } from 'express';

export const catchErrors = (requestHandler: RequestHandler): RequestHandler => {
  return async (req, res, next): Promise<any> => {
    try {
      console.log(req.body) **// returns requestHandler's req parameter //**

      return await requestHandler(req, res, next);
    } catch (error) {
      next(error);
    }
  };
};

It is used to wrap around REST API controllers to catch errors and pass it into an error handling middleware. A brief example of such usage would be this:

import {catchErrors} from './error'
export const fetchData = catchErrors(async (req: Request, res: Response) => {
  /// perform data fetching here ///
  return res.status(200).send()

})

I am confused as to how the catchErrors function works. To my understanding, requestHandler parameter refers to the original REST controller callback. However, the next part of catchError where it says return async (req, res, next): Promise<any> => {...} Where does this (req, res, next) come from? I tried console logging the req.body and it turned out to be the request body of the requestHandler parameter parsed above. I do not understand how the requestHandler's (req, res, next) can be referenced in this way instead of say requestHandler.req (which does not work)?

GitHub link where I found this code: https://github.com/oldboyxx/jira_clone/blob/master/api/src/errors/asyncCatch.ts

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

catchErrors is just a helper function to return a middleware function from another middleware function, enhancing or adding features. in your case, think of fetchData as

 async (req, res, next): Promise<any> => {
    try {
      console.log(req.body) **// returns requestHandler's req parameter //**

      const fetchFunction = async (req: Request, res: Response) => {
           /// perform data fetching here ///
           return res.status(200).send()

      }
      return await fetchFunction(req, res, next);
    } catch (error) {
      next(error);
    }
  };


which is a valid middleware for express. take a look at higher order function, decorator pattern and closures which are the same concept.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda