I created an user entity with uid , username , email now i am giving unique : true to username , email now i want to learn how to handle the exception with multiple unique constraints
import { Book } from 'src/book/entities/book.entity';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
OneToMany,
} from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
uid: string;
@Column({ type: 'varchar', length: 120, unique: true })
username: string;
@Column({ type: 'varchar', length: 120, unique: true })
email: string;
@Column({ type: 'varchar' })
password: string;
/*
* Create and Update Date Columns
*/
@OneToMany(() => Book, (book) => book.user) books: Book[];
@CreateDateColumn({ type: 'timestamp' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamp' })
updatedAt!: Date;
}
and my controller
async registerUser(@Body() userDto: UserDto) {
try {
const user = await this.userService.create(userDto);
delete user.password;
return user;
} catch (error) {
if (error.code === '23505') {
throw new BadRequestException({ error: error });
} else {
throw new BadRequestException({ error: error });
}
}
}
in above code i want to handle the exception if username , email is already exist then send the response