NestJS | 이미 등록되어있는 유저 에러 처리(Unique)

임동혁 Ldhbenecia·2023년 8월 22일
0

NestJS

목록 보기
1/4
post-thumbnail

본 포스팅은 따라하면서 배우는 NestJS 를 보고 학습하며 정리한 내용임을 밝힙니다.

유저 이름에 유니크한 값 주기

이미 등록되어있는 유저네임을 사용하려고 하는 경우 에러 처리 구현

회원가입 기능을 구현할 때 이미 등록이 되어있는 name이 중복되어서 등록되는 경우를 방지하기 위한 방법입니다.

두 가지 방법

  1. Repository에서 findOne 메소드를 이용해서 이미 같은 유저네임을 가진 아이디가 있는지 확인하고 없다면 데이터를 저장하는 방법
    하지만 이 방법은 데이터베이스 처리를 두 번 해줘야합니다.
  2. 데이터베이스 레벨에서 만약 같은 이름을 가진 유저가 있다면 에러를 던져주는 방법

두 번째 방법으로 구현

  • user.entity.ts에서 원하는 유니크한 값을 원하는 필드 값을 정해주면 됨

Entity 수정

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm';

@Entity()
@Unique(['username'])
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  password: string;
}

그냥 @Entity() 밑에 유니크 코드만 한 줄 작성하면 끝이납니다.
'username'이라는 값에 대해서 유니크한 값을 가진다는 뜻입니다.

이러면 같은 이름을 가진 유저를 등록하려고 할 때 바로 에러를 던지게 됩니다.
하지만 이 경우 한가지 고려를 해야할 사항이 있습니다.

Postman으로 체크해볼시 500에러를 던지기 때문에 클라이언트나 서버측에서 바로 문제를 알아보기 힘들게 됩니다.

왜 500에러가?

이유는 NestJS에서 에러가 발생하고 그걸 try catch 구문인 catch에서 잡아주지 않는다면 이 에러가 Controller 레벨로 가서 그냥 500에러를 던진다고합니다.

이러기 떄문에 try-catch 구문을 사용해서 에러처리를 해야합니다.

try-catch 구문의 중요성,,

import { DataSource, Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { Injectable } from '@nestjs/common';
import { AuthCredentialsDto } from '../dto/auth-credential.dto';

@Injectable()
export class UserRepository extends Repository<User> {
  constructor(dataSource: DataSource) {
    super(User, dataSource.createEntityManager());
  }

  async createUsers(authCredentialsDto: AuthCredentialsDto): Promise<void> {
    const { username, password } = authCredentialsDto;

    const user = this.create({ username, password });

    try {
      await this.save(user);
    } catch (error) {
      console.log('error', error);
    }
  }
}

그래서 회원가입 코드에서 try-catch구문을 통해 에러코드를 한번 확인해보았습니다.

이런식으로 에러코드가 쭉 뜨는데 여기서 code: '23505'를 확인할 수 있습니다. 500 에러에 대한 이 경우의 에러코드는 23505라는 뜻입니다.

import { DataSource, Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { ConflictException, Injectable, InternalServerErrorException } from '@nestjs/common';
import { AuthCredentialsDto } from '../dto/auth-credential.dto';

@Injectable()
export class UserRepository extends Repository<User> {
  constructor(dataSource: DataSource) {
    super(User, dataSource.createEntityManager());
  }

  async createUsers(authCredentialsDto: AuthCredentialsDto): Promise<void> {
    const { username, password } = authCredentialsDto;

    const user = this.create({ username, password });

    try {
      await this.save(user);
    } catch (error) {
      if (error.code == '23505') {
        throw new ConflictException('Existing username');
      } else {
        throw new InternalServerErrorException();
      }
    }
  }
}

그래서 if-else문을 통해서 에러코드가 23505일 경우 이미 유저네임이 존재한다는 에러메세지를 던졌고 이 외에는 500에러가 출력되게 설정하였습니다.

말끔히 해결완료

profile
지극히 평범한 공대생

0개의 댓글

관련 채용 정보