Handling business logic exceptions in NestJS typically follows these steps:
1. Define Custom Exception Classes
By leveraging the HttpException class provided by NestJS, you can create custom exception classes to represent specific business logic issues. For example, if you need to throw an exception when a user is not found in the user service, define a UserNotFoundException:
typescriptimport { HttpException, HttpStatus } from '@nestjs/common'; export class UserNotFoundException extends HttpException { constructor() { super('User not found', HttpStatus.NOT_FOUND); } }
2. Throw Custom Exceptions in Services
In your service, when a specific business logic error is detected, throw a custom exception. For example, in a user service, when attempting to retrieve a non-existent user, throw the previously defined UserNotFoundException:
typescript@Injectable() export class UsersService { constructor(@InjectRepository(User) private readonly userRepository: Repository<User>) {} async findOne(id: string): Promise<User> { const user = await this.userRepository.findOne(id); if (!user) { throw new UserNotFoundException(); } return user; } }
3. Exception Filters
NestJS supports exception filters that capture exceptions across the entire application. Define a global exception filter or one specific to controllers or routes.
typescriptimport { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status = exception.getStatus(); const exceptionResponse = exception.getResponse(); response .status(status) .json({ statusCode: status, timestamp: new Date().toISOString(), path: request.url, message: exceptionResponse['message'] || exceptionResponse, }); } }
Register the filter in your module:
typescript@Module({ // ...other configurations providers: [ { provide: APP_FILTER, useClass: HttpExceptionFilter, }, ], }) export class AppModule {}
4. Respond to the Client
After an exception is thrown and handled by the filter, the client receives a structured response containing relevant details like HTTP status code and error message.
Example:
Suppose a client attempts to retrieve a non-existent user.
Request:
httpGET /users/123
Response:
json{ "statusCode": 404, "timestamp": "2023-03-10T10:00:00.000Z", "path": "/users/123", "message": "User not found" }
These steps ensure clear organization and consistent handling of business logic exceptions in NestJS, while providing useful error information to clients.