Sitemap
Asif Raza

Asif Raza

Senior Full-Stack Developer | AI/ML, React, Next.js, Node.js & TypeScript. Exploring AI/ML, modern web architecture & UI/UX. Building. Learning. Sharing.

asyncHandler instead of try and catch

2 min readNov 11, 2024

--

asyncHandler

The asyncHandler function you've defined is a utility function commonly used in Node.js applications, especially with frameworks like Express.js, to handle asynchronous operations in route handlers. Let's break down what it does:

javascriptCopy code
const asyncHandler = (requestHandler) => {
return (req, res, next) => {
Promise
.resolve(
requestHandler(req, res, next)
)
.catch(
(err) => next(err)
)
}
}

Explanation:

  1. Function Definition:
  • asyncHandler is a higher-order function that takes a requestHandler function as an argument. This requestHandler function is expected to handle incoming HTTP requests, typically in the context of an Express.js route handler.
  1. Returned Function:
  • Inside asyncHandler, it returns another function (req, res, next) => { ... }. This inner function is the actual middleware function that Express.js will call when a matching route is requested.
  1. Promise Resolution:
  • Promise.resolve(requestHandler(req, res, next)): This line wraps the invocation of requestHandler in Promise.resolve(). This is crucial because it ensures that requestHandler is always executed as a Promise, allowing you to use async/await or .then() syntax inside requestHandler.
  1. Error Handling:
  • .catch((err) => next(err)): If requestHandler encounters an error (i.e., throws an exception or returns a rejected Promise), .catch() captures that error and passes it to Express's next() function. This effectively forwards the error to Express's default error handling middleware or any custom error handling middleware you have defined.

Get Asif Raza’s stories in your inbox

Join Medium for free to get updates from this writer.

Usage Example:

You would use asyncHandler to wrap your route handler functions to ensure proper error handling for asynchronous operations:

javascriptCopy code
const express = require('express');
const app = express();
const asyncHandler = (requestHandler) => {
return (req, res, next) => {
Promise
.resolve(
requestHandler(req, res, next)
)
.catch(
(err) => next(err)
)
}
}
// Example route using asyncHandler
app.get('/example', asyncHandler(async (req, res, next) => {
// Async operations such as database queries or API calls
const result = await someAsyncOperation();
res.json(result);
}));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

In this example, the asyncHandler middleware wraps the async route handler for /example, ensuring that any errors thrown within someAsyncOperation() are properly caught and forwarded to Express's error handling middleware (next(err)). This pattern helps to avoid repetitive try/catch blocks in every async route handler, promoting cleaner and more maintainable code.

--

--

Senior Full-Stack Developer | AI/ML, React, Next.js, Node.js & TypeScript. Exploring AI/ML, modern web architecture & UI/UX. Building. Learning. Sharing.

See more from me