Errors

  1. Wrong choice in Nest

    1. Throwing an exception
    2. Use library-specific response objects
    3. Create interceptors and use exception filters

    Additionally, nest has helper methods for all common error responses, including helper classes.


  2. Throw an exception

    In the service file:

    1
    2
    3
    4
    5
    6
    7
    findOne(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;
    }


  1. Help class

    Including NotFoundException, InternalServiceErrorException, BadRequestException, etc.

    1
    2
    3
    4
    5
    6
    7
    findOne(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;
    }


  1. Nest’s built-in exception layer automatically catches exceptions

    Similar to express-error to automatically process packages.


Share