loading...
Cover image for Note to Self: Handling Exception on Nest JS and Interceptor

Note to Self: Handling Exception on Nest JS and Interceptor

anzhari profile image Anzhari Purnomo ・1 min read

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);
    }
}

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

Posted on by:

anzhari profile

Anzhari Purnomo

@anzhari

Founded Merahputih.id in early career, now focusing on the technical aspect of product building.

Discussion

markdown guide