@develop-x/nest-exception v1.0.22
@develop-x/nest-exception
Overview
@develop-x/nest-exception
is a NestJS package that provides comprehensive exception handling capabilities for your applications. It includes custom business exceptions, global exception filters, and OpenTelemetry integration for better error tracking and observability.
Installation
npm install @develop-x/nest-exception
Features
- Business Exception Class: Custom exception class for business logic errors
- Global Exception Filter: Centralized exception handling with consistent error responses
- OpenTelemetry Integration: Automatic trace ID inclusion in error responses
- Structured Error Responses: Consistent error format across your application
- Logging Integration: Automatic error logging with trace correlation
- Customizable Error Codes: Support for custom error codes and messages
Usage
Module Import
The exception handling is typically configured globally in your application:
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { BaseGlobalExceptionFilter } from '@develop-x/nest-exception';
@Module({
providers: [
{
provide: APP_FILTER,
useClass: BaseGlobalExceptionFilter,
},
],
})
export class AppModule {}
Business Exception
Use the BusinessException
class for business logic errors:
import { Injectable } from '@nestjs/common';
import { BusinessException } from '@develop-x/nest-exception';
@Injectable()
export class UserService {
async getUserById(id: string) {
const user = await this.findUser(id);
if (!user) {
throw new BusinessException(
1001, // Error code
{ userId: id }, // Additional context
404, // HTTP status code
'User not found' // Default message
);
}
return user;
}
async createUser(userData: any) {
if (!userData.email) {
throw new BusinessException(
1002,
{ field: 'email' },
400,
'Email is required'
);
}
// Create user logic...
}
}
Custom Error Codes
Define your application's error codes:
// error-codes.ts
export const ErrorCodes = {
USER_NOT_FOUND: 1001,
INVALID_EMAIL: 1002,
INSUFFICIENT_PERMISSIONS: 1003,
RESOURCE_ALREADY_EXISTS: 1004,
VALIDATION_FAILED: 1005,
} as const;
// Usage
import { BusinessException } from '@develop-x/nest-exception';
import { ErrorCodes } from './error-codes';
throw new BusinessException(
ErrorCodes.USER_NOT_FOUND,
{ userId: '123' },
404,
'User not found'
);
API Reference
BusinessException
Custom exception class for business logic errors.
Constructor
constructor(
errorCode?: number, // Custom error code (default: 9999)
args?: Record<string, any>, // Additional context data
statusCode?: number, // HTTP status code (default: 400)
defaultMessage?: string // Error message (default: 'Business error')
)
Properties
errorCode: number
- Custom error code for the business exceptionargs: Record<string, any>
- Additional context datastatusCode: number
- HTTP status codedefaultMessage: string
- Error message
Example
const exception = new BusinessException(
1001,
{ userId: '123', action: 'delete' },
403,
'User cannot be deleted'
);
BaseGlobalExceptionFilter
Global exception filter that handles all unhandled exceptions.
Features
- Handles
BusinessException
instances with custom formatting - Handles standard
HttpException
instances - Handles unexpected errors with generic error responses
- Includes OpenTelemetry trace IDs in error responses
- Logs errors with appropriate log levels
Error Response Format
All errors follow a consistent response structure:
interface ErrorResponse {
code: number; // Error code or HTTP status
message: string; // Error message
data: null; // Always null for errors
meta: {
traceId?: string; // OpenTelemetry trace ID
timestamp: string; // ISO timestamp
};
}
Response Examples
Business Exception Response
{
"code": 1001,
"message": "User not found",
"data": null,
"meta": {
"traceId": "1234567890abcdef",
"timestamp": "2023-12-01T10:30:00.000Z"
}
}
HTTP Exception Response
{
"code": 404,
"message": "Not Found",
"data": null,
"meta": {
"traceId": "1234567890abcdef",
"timestamp": "2023-12-01T10:30:00.000Z"
}
}
Unexpected Error Response
{
"code": 500,
"message": "Internal server error",
"data": null,
"meta": {
"traceId": "1234567890abcdef",
"timestamp": "2023-12-01T10:30:00.000Z"
}
}
Advanced Usage
Custom Exception Filter
You can extend the base exception filter for custom behavior:
import { Catch, ArgumentsHost } from '@nestjs/common';
import { BaseGlobalExceptionFilter } from '@develop-x/nest-exception';
@Catch()
export class CustomExceptionFilter extends BaseGlobalExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// Add custom logic before handling
this.logCustomMetrics(exception);
// Call parent handler
super.catch(exception, host);
}
private logCustomMetrics(exception: unknown) {
// Custom metrics logging
}
}
Validation Exception Handling
Handle validation errors from class-validator:
import { ValidationPipe, BadRequestException } from '@nestjs/common';
import { BusinessException } from '@develop-x/nest-exception';
// Custom validation pipe
export class CustomValidationPipe extends ValidationPipe {
constructor() {
super({
exceptionFactory: (errors) => {
const firstError = errors[0];
const firstConstraint = Object.values(firstError.constraints || {})[0];
return new BusinessException(
1005, // VALIDATION_FAILED
{
field: firstError.property,
value: firstError.value,
constraints: firstError.constraints
},
400,
firstConstraint || 'Validation failed'
);
},
});
}
}
// Usage in main.ts
app.useGlobalPipes(new CustomValidationPipe());
Error Context Enhancement
Add more context to your exceptions:
import { Injectable } from '@nestjs/common';
import { BusinessException } from '@develop-x/nest-exception';
@Injectable()
export class OrderService {
async processOrder(orderId: string, userId: string) {
try {
// Order processing logic
} catch (error) {
throw new BusinessException(
2001,
{
orderId,
userId,
timestamp: new Date().toISOString(),
originalError: error.message,
stackTrace: error.stack
},
500,
'Order processing failed'
);
}
}
}
Integration Examples
With Logging Service
import { Catch, ArgumentsHost, Injectable } from '@nestjs/common';
import { BaseGlobalExceptionFilter } from '@develop-x/nest-exception';
import { LoggerService } from '@develop-x/nest-logger';
@Injectable()
@Catch()
export class LoggingExceptionFilter extends BaseGlobalExceptionFilter {
constructor(private readonly logger: LoggerService) {
super();
}
catch(exception: unknown, host: ArgumentsHost) {
// Log the exception with context
this.logger.error('Exception caught', {
exception: exception instanceof Error ? exception.message : exception,
stack: exception instanceof Error ? exception.stack : undefined,
context: host.getType(),
});
super.catch(exception, host);
}
}
With Monitoring Service
import { Injectable } from '@nestjs/common';
import { BusinessException } from '@develop-x/nest-exception';
@Injectable()
export class MonitoredService {
constructor(private readonly metricsService: MetricsService) {}
async riskyOperation() {
try {
// Risky operation
} catch (error) {
// Increment error metrics
this.metricsService.incrementCounter('business_errors', {
errorCode: '3001',
service: 'MonitoredService'
});
throw new BusinessException(
3001,
{ operation: 'riskyOperation' },
500,
'Operation failed'
);
}
}
}
Testing
Unit Testing Exceptions
import { Test, TestingModule } from '@nestjs/testing';
import { BusinessException } from '@develop-x/nest-exception';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should throw BusinessException when user not found', async () => {
jest.spyOn(service, 'findUser').mockResolvedValue(null);
await expect(service.getUserById('123')).rejects.toThrow(BusinessException);
try {
await service.getUserById('123');
} catch (error) {
expect(error).toBeInstanceOf(BusinessException);
expect(error.errorCode).toBe(1001);
expect(error.args).toEqual({ userId: '123' });
}
});
});
Integration Testing
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { BaseGlobalExceptionFilter } from '@develop-x/nest-exception';
import * as request from 'supertest';
describe('Exception Handling (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
providers: [
{
provide: APP_FILTER,
useClass: BaseGlobalExceptionFilter,
},
],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('should return formatted error response', () => {
return request(app.getHttpServer())
.get('/users/nonexistent')
.expect(404)
.expect((res) => {
expect(res.body).toHaveProperty('code');
expect(res.body).toHaveProperty('message');
expect(res.body).toHaveProperty('data', null);
expect(res.body).toHaveProperty('meta');
expect(res.body.meta).toHaveProperty('timestamp');
});
});
});
Best Practices
- Consistent Error Codes: Use a centralized error code registry
- Meaningful Messages: Provide clear, actionable error messages
- Context Information: Include relevant context in the
args
parameter - Appropriate Status Codes: Use correct HTTP status codes
- Security Considerations: Don't expose sensitive information in error messages
- Logging: Always log errors with sufficient context for debugging
Dependencies
@nestjs/common
: NestJS common utilities@develop-x/nest-logger
: Logging service integration@opentelemetry/api
: OpenTelemetry API for trace integrationexpress
: Express.js types for request/response handling
License
ISC
Support
For issues and questions, please refer to the project repository or contact the development team.
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago