Skip to main content

Command Palette

Search for a command to run...

Simplifying Asynchronous Error Handling in Express.js with catchAsync

Published
1 min readView as Markdown
Simplifying Asynchronous Error Handling in Express.js with catchAsync
F

Hi, I'm Farhad Hossain, a passionate web developer on a journey to build impactful software and solve real-world problems. I share coding tips, tutorials, and my growth experiences to inspire others.

Purpose:

catchAsync handles asynchronous errors in Express.js routes by catching rejected promises and passing them to the error-handling middleware.

Key Concepts:

  • Higher-Order Function: Takes an async function and returns a new function that wraps it.

  • Error Handling: Automatically catches errors and calls next(err) to pass them to Express error handlers.

Code Explanation:

const catchAsync = (fn: RequestHandler) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(err => next(err));
  };
};

export default catchAsync;

Usage Example:

Instead of:

app.get('/example', async (req, res, next) => {
  try {
    // Async code
  } catch (err) {
    next(err);
  }
});

Use catchAsync:

app.get('/example', catchAsync(async (req, res, next) => {
  // Async code
}));

Benefits:

  • Cleaner Code: Eliminates repetitive try-catch blocks.

  • Consistency: Uniform error handling.

  • Readability: More concise route handlers.

S

Hey Forhad I am glad that you share this.It's really helpful to stream line code. Thanks.

1

More from this blog