async-catch-wrapper
v1.0.0
Published
catch async wrapper to avoid use of try catch in your code and can catch proper errors
Downloads
4
Maintainers
Keywords
Readme
CatchAsync Utility
Overview
catchAsync is a utility function designed to handle errors in asynchronous functions across different parts of your NestJS application. This wrapper can be used for:
- Request & Response Handlers (Controllers & Middleware)
- Kafka Consumers & Producers
- Service Methods
- Middleware Handlers
By using this function, you ensure that all asynchronous errors are properly caught and handled without needing repetitive try-catch blocks in your code.
Installation
Using Yarn
yarn add async-catch-wrapperUsing NPM
npm install async-catch-wrapperImplementation
import { HttpException } from "@nestjs/common";
export const catchAsync = <T extends (...args: any[]) => Promise<any>>(fn: T) => {
return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
try {
return await fn(...args);
} catch (error) {
console.error("Error:", error);
if (error instanceof HttpException) {
throw error;
}
if (error.name === "KafkaError") {
console.error("Kafka Error:", error.message);
throw new HttpException(error.message || "KafkaError", error.status || 400);
}
throw new HttpException(error.message || "Internal Server Error", error.status || 500);
}
};
};Usage Examples
1. Using catchAsync in a Service Method
import { Injectable, HttpException } from "@nestjs/common";
import { DatabaseService } from "modules/database/database.service";
import { catchAsync } from "common/utils/catchAsync";
@Injectable()
export class UserService {
constructor(private readonly databaseService: DatabaseService) {}
public getUserById = catchAsync(async (userId: string) => {
const user = await this.databaseService.findUserById(userId);
if (!user) {
throw new HttpException("User not found", 404);
}
return user;
});
}2. Using catchAsync in a Kafka Consumer
import { Injectable } from "@nestjs/common";
import { KafkaService } from "modules/kafka/kafka.service";
import { catchAsync } from "common/utils/catchAsync";
@Injectable()
export class OrderConsumer {
constructor(private readonly kafkaService: KafkaService) {}
public handleOrderMessage = catchAsync(async (message) => {
console.log("Processing order message:", message);
// Process the Kafka message
});
}3. Using catchAsync in a Controller
import { Controller, Get, Param } from "@nestjs/common";
import { UserService } from "modules/user/user.service";
import { catchAsync } from "common/utils/catchAsync";
@Controller("users")
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(":id")
public getUser = catchAsync(async (req, res) => {
const user = await this.userService.getUserById(req.params.id);
res.json(user);
});
}4. Using catchAsync in Middleware
import { NextFunction, Request, Response } from "express";
import { JwtService } from "@nestjs/jwt";
import { HttpException } from "@nestjs/common";
import { catchAsync } from "common/utils/catchAsync";
export const authMiddleware = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) throw new HttpException("Unauthorized", 401);
const payload = await new JwtService().verifyAsync(token, { secret: process.env.JWT_SECRET });
req.user = payload;
next();
});Benefits of catchAsync
✅ Reduces Code Duplication – No need for try-catch blocks in every function.
✅ Centralized Error Handling – All errors are caught and processed in one place.
✅ Improves Readability – Code is cleaner and easier to maintain.
✅ Works for All Use Cases – API routes, Kafka, Middleware, Services, and more.
License
This project is licensed under the MIT License.
Conclusion
The catchAsync wrapper is a powerful tool to simplify error handling in your NestJS project. Implement it once and use it everywhere!
If you have any questions or need improvements, feel free to contribute. 🚀
