DEV Community

Cover image for Note to Self: Handling Exception on Nest JS and Interceptor
Anzhari Purnomo
Anzhari Purnomo

Posted on

Note to Self: Handling Exception on Nest JS and Interceptor

How do you handle exceptions from the service provider? For example, I have this service "UserService.ts":

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './users.entity';
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from './dto/create-user.dto';
import { AuthenticateUserDto } from './dto/authenticate-user.dto'

@Injectable()
export class UsersService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
    ) {}

    async register(createUserDto: CreateUserDto): Promise<User | undefined> {
        const user = new User();
        const saltRounds = 10;

        user.username = createUserDto.username;
        user.email = createUserDto.email; 
        user.password = bcrypt.hashSync(createUserDto.password, saltRounds)

        return this.userRepository.save(user);
    }
}

Enter fullscreen mode Exit fullscreen mode

How do I handle exceptions generated from "register" method? For example, if there is an exception caused by unique constraint when I insert a value.

Currently I am using Interceptor Exception Mapping on the controller method, but I feel it is not quite intuitive yet for me.

Cover Image: Glenn Carstens-Peters

Top comments (0)