
Security News
Deno Goes the Way of the Dinosaur
Cloudflare is acquiring Deno’s team, which will provide another year of bug fixes and security updates before ending support for the runtime.
nestjs-exception-handler
Advanced tools
A production-grade global exception handling system for NestJS applications
A production-grade global exception handling system for NestJS applications that provides consistent global error response format for all types of errors.
When building NestJS applications, error handling can become inconsistent across different scenarios:
This package ensures every error response follows the same standardized format, making your API consistent and easier to consume by clients.
any typesnpm install nestjs-exception-handler
Or with yarn:
yarn add nestjs-exception-handler
The simplest way to use the package is to apply the global exception filter:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { GlobalExceptionFilter } from 'nestjs-exception-handler';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
}),
);
app.useGlobalFilters(new GlobalExceptionFilter());
await app.listen(3000);
}
bootstrap();
For more control, you can use the module registration:
import { Module } from '@nestjs/common';
import { ExceptionHandlerModule } from 'nestjs-exception-handler';
@Module({
imports: [
ExceptionHandlerModule.forRoot({
enableLogging: true,
hideStackTrace: true,
}),
],
})
export class AppModule {}
Every error response follows this exact structure:
interface ErrorResponse {
success: false;
message: string;
errorMessages: {
path: string;
message: string[];
}[];
}
{
"success": false,
"message": "Bad Request Exception",
"errorMessages": [
{
"path": "http_error",
"message": ["email must be an email", "password must be longer than 8 characters"]
}
]
}
When using ValidationPipe with class-validator, errors are automatically normalized:
// DTO
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
}
Response:
{
"success": false,
"message": "Bad Request Exception",
"errorMessages": [
{
"path": "http_error",
"message": ["email must be an email", "password must be longer than or equal to 8 characters"]
}
]
}
Throwing HTTP exceptions manually:
throw new BadRequestException('User already exists');
Response:
{
"success": false,
"message": "Bad Request Exception",
"errorMessages": [
{
"path": "http_error",
"message": ["User already exists"]
}
]
}
Other supported HTTP exceptions:
NotFoundException - Returns "Not Found Exception"UnauthorizedException - Returns "Unauthorized Exception"ForbiddenException - Returns "Forbidden Exception"ConflictException - Returns "Conflict Exception"The package automatically handles common Prisma errors:
// When trying to create a user with duplicate email
Response:
{
"success": false,
"message": "Database error",
"errorMessages": [
{
"path": "email",
"message": ["A record with this email already exists."]
}
]
}
Response:
{
"success": false,
"message": "Database error",
"errorMessages": [
{
"path": "userId",
"message": ["The referenced userId does not exist."]
}
]
}
Response:
{
"success": false,
"message": "Database error",
"errorMessages": [
{
"path": "record",
"message": ["The requested record does not exist."]
}
]
}
For unexpected errors:
{
"success": false,
"message": "Internal Server Error",
"errorMessages": [
{
"path": "server",
"message": ["Something went wrong"]
}
]
}
Stack traces are never leaked in production (configurable).
When a client requests a route that doesn't exist, the package automatically converts it to the standardized format:
{
"success": false,
"message": "Route Not Found",
"errorMessages": [
{
"path": "route",
"message": ["Cannot GET /users/test"]
}
]
}
The response includes:
POST to non-existent route:
{
"success": false,
"message": "Route Not Found",
"errorMessages": [
{
"path": "route",
"message": ["Cannot POST /api/user/test"]
}
]
}
DELETE on non-existent route:
{
"success": false,
"message": "Route Not Found",
"errorMessages": [
{
"path": "route",
"message": ["Cannot DELETE /api/items/123"]
}
]
}
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
const config =
process.env.NODE_ENV === 'production'
? { enableLogging: true, hideStackTrace: true }
: { enableLogging: true, hideStackTrace: false };
app.useGlobalFilters(new GlobalExceptionFilter(config));
Extend the package for custom error handling:
import { ExceptionFormatter, ErrorMessage } from 'nestjs-exception-handler';
export class CustomExceptionFormatter implements ExceptionFormatter {
supports(exception: unknown): boolean {
return exception instanceof CustomError;
}
format(exception: unknown): ErrorMessage[] {
const error = exception as CustomError;
return [
{
path: error.field,
message: [error.message],
},
];
}
message(_exception: unknown): string {
return 'Custom error occurred';
}
}
// Constructor
new GlobalExceptionFilter(service: ExceptionHandlerService, config?: ExceptionHandlerConfig)
// Config options
interface ExceptionHandlerConfig {
enableLogging?: boolean; // Default: true
hideStackTrace?: boolean; // Default: false
}
// Register globally
ExceptionHandlerModule.forRoot(config?)
// Register for specific feature
ExceptionHandlerModule.forFeature(config?)
// Register custom formatter
service.registerFormatter(formatter: ExceptionFormatter)
// Format exception
service.formatException(exception: unknown): { errors: ErrorMessage[]; message: string }
// Get all registered formatters
service.getAllFormatters(): ExceptionFormatter[]
| Error Type | Example |
|---|---|
| Validation | message: ["email must be an email"] |
| HttpException | message: ["User already exists"] |
| Prisma P2002 | message: ["A record with this email already exists."] |
| 404 Not Found | message: ["Cannot GET /unknown-route"] |
| Unknown | message: ["Something went wrong"] |
Contributions are welcome! Please feel free to submit a Pull Request.
git checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)MIT
Nurul Islam Rimon
FAQs
A production-grade global exception handling system for NestJS applications
The npm package nestjs-exception-handler receives a total of 0 weekly downloads. As such, nestjs-exception-handler popularity was classified as not popular.
We found that nestjs-exception-handler demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Security News
Cloudflare is acquiring Deno’s team, which will provide another year of bug fixes and security updates before ending support for the runtime.

Security News
Anthropic’s free OSS Scanner uses Mythos and other Claude models to find open source vulnerabilities and send maintainers reports with proposed fixes.

Security News
On Front Lines’ Early Adopters: CISO podcast, Andrew Becherer shares lessons from Datadog, weighs the long-term costs of AI-built tools, and explains how founders can actually gain a CISO’s trust.