Wrong choice in Nest
- Throwing an exception
- Use library-specific response objects
- Create interceptors and use exception filters
Additionally, nest has helper methods for all common error responses, including helper classes.
Throw an exception
In the service file:
1
2
3
4
5
6
7findOne(id: string){
const coffee = this.coffees.find(item => item.id === +id);
if(!coffee){
throw new HttpException(`Coffee #${id} not found`, HttpStatus.NOT_FOUND);
}
return coffee;
}
Help class
Including NotFoundException, InternalServiceErrorException, BadRequestException, etc.
1
2
3
4
5
6
7findOne(id: string){
const coffee = this.coffees.find(item => item.id === +id);
if(!coffee){
throw new NotFoundException(`Coffee #${id} not found`); //Replace here, but return the same
}
return coffee;
}
Nest’s built-in exception layer automatically catches exceptions
Similar to express-error to automatically process packages.