Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda