skip to Main Content

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


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

    function errorHandler (err, req, res, next) {
       customErrorHandler(err);
    }
    
    Login or Signup to reply.
  2. Sounds like you want to use something like express-async-handler and to register customErrorHandler as the global error handler

    import asyncHandler from "express-async-handler";
    
    export const login = asyncHandler(async (req, res) => {
      // code
    });
    

    and

    // must accept four arguments
    const customErrorHandler = (err, req, res, next) => {
      // just an example
      console.error(err);
      res.sendStatus(err.status ?? 500);
    };
    
    // register error handling middleware after routes
    app.use(customErrorHandler);
    

    Note: express-async-handler won’t be required if you’re using Express v5.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search