#Typeorm handle multiple unique value exception in controller

1 messages · Page 1 of 1 (latest)

lament parrot
#

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

lavish talon
#

You can work on a better solution by checking if email / username exists in the DTO class, it is a much cleaner solution.
If you don't want to implement the check in the DTO, you can check if the email / username in the service and throw the exception there and catch it in the controller.