I have a function, that takes a middleware function, wraps it into a try catch block and then returns back a middleware function.
tryCatch.ts
import { Request, Response, NextFunction } from "express";
export default function tryCatch(controller: (req: Request, res: Response, next?: NextFunction) => Promise<any>) {
return async function (req: Request, res: Response, next: NextFunction): Promise<void> {
try {
await controller(req, res, next);
} catch (error) {
// do some logging first, then call next
return next(error);
}
}
};
Route handler
import express from 'express';
import tryCatch from './tryCatch';
import someAsyncHandler from './controller/someAsyncHandler';
const router = express.Router({ mergeParams: true });
router.post('/foo', someAsyncHandler);
// ^ this works
router.post('/bar', tryCatch( someAsyncHandler ));
// ^ this doesn't work
It gives the following error:
No overload matches this call. The last overload gave the following error.
Argument of type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is not assignable to parameter of type 'Application<Record<string, any>>'.
Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more. ts(2769)
Before switching to Typescript, this worked fine. What am I doing wrong or is it just Typescript?