Note to Self: Handling Exception on Nest JS and Interceptor
Anzhari Purnomo
Posted on September 15, 2020
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
💖 💪 🙅 🚩
Anzhari Purnomo
Posted on September 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.