abs-nestjs-http-exception-filter-middleware
v0.0.4
Published
`HttpExceptionFilterMiddleware` is a custom http exception filter middleware that displays the error response with the following json format
Readme
HttpExceptionFilterMiddleware Documentation
HttpExceptionFilterMiddleware is a custom http exception filter middleware that displays the error response with the following json format
{
"message": "A short description of the error",
"statusCode": 400,
"timestamp": "2024-11-19T22:59:47.025Z",
"errorCode": "000003",
"description": "A descriptive or long description of the error"
}Installation
To install the necessary dependencies, run:
npm install abs-nestjs-http-exception-filter-middlewareUsage with NestJS
- Import the HttpExceptionFilterMiddleware into your main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilterMiddleware } from 'abs-nestjs-exception-filter-middleware';
import { config } from './config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// use global http exception filter middleware
app.useGlobalFilters(new HttpExceptionFilterMiddleware());
await app.listen(config.port);
}
bootstrap();- Extend the ErrorCodes class
import { HttpStatus } from '@nestjs/common';
import { ErrorCodes } from 'abs-nestjs-exception-filter-middleware';
export class CustomErrors extends ErrorCodes {
public static CUSTOM_ERROR = {
CODE: '000021',
STATUS_CODE: HttpStatus.INTERNAL_SERVER_ERROR,
MESSAGE: 'Something went wrong. Please try again later',
DESCRIPTION:
'An internal issue occurred. Either you or the system may have done something wrong. Please try again later or contact support.',
};
public static CUSTOM_ERROR_WITH_PARAMS ({ args1, args2 }) {
CODE: '000021',
STATUS_CODE: HttpStatus.INTERNAL_SERVER_ERROR,
MESSAGE: `Passed params ${args1} and ${args2}`,
DESCRIPTION:
'An internal issue occurred. Either you or the system may have done something wrong. Please try again later or contact support.',
}
}- Somewhere in your code, you can import the helper
throwExceptionErrorthen use it to throw your Custom Error
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { throwExceptionError } from 'abs-nestjs-exception-filter-middleware';
import { CustomErrors } './custom-errors.constants';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('/error-1')
someMethod(): string {
throwExceptionError(CustomErrors.CUSTOM_ERROR);
}
@Get('/error-2')
someMethod(): string {
throwExceptionError(CustomErrors.CUSTOM_ERROR_WITH_PARAMS({ args1: 'test1', args2: 'test2'}));
}
}