I’m developing an express application and instead of writing a try-catch block for each of the async request handler functions i wanna create a wrapper function that receives them as an argument and puts them in a try-catch block .
for example instead of :
export const login = async(req,res,next)=>{
try{
// code
} catch(err){
//code }
I wanna do this :
export const login = tryCatch(async(req,res,next)=>{
// handler function code without try-catch block
}
my code for tryCatch function is like this :
const tryCatch = (func: RequestHandler): RequestHandler => {
return (req,res,next) => {
try {
func(req,res,next);
} catch(err) {
customErrorHandler(err)
}
}
}
the problem is that when i encounter an error for example duplicate-key error from mongodb.
the catch block didn’t pick up the error. it doesn’t even reach the catch block.
everything happens in the try block and when an error occurs my app crashes.
2
Answers
You can create a error handler like so. This will run for all requests that result in an error. See The default error handler here.
Sounds like you want to use something like express-async-handler and to register
customErrorHandler
as the global error handlerand
Note: express-async-handler won’t be required if you’re using Express v5.