강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

HenaPapa님의 프로필 이미지
HenaPapa

작성한 질문수

따라하며 배우는 NestJS

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

[자문자답] 디비 중복 오류 검출 방법 변경? QueryFailedError

작성

·

919

1

자문자답입니다.

강사님 코드에서는 아래와 같이 error.code 값을 비교해서 검사하는데요.


try {

await this.save(user);

} catch (error) {

if (error.code === '23505') {

throw new ConflictException('Existing username');

} else {

throw new InternalServerErrorException();

}

}


이 방법은 특정 데이터베이스(postgres?) 의존적일 가능성이 있어 보입니다.

좀더 일반적인 방법을 찾아보다가 발견한 건데요.

오류를 콘솔 로그에서 확인해보면, QueryFailedError 객체로 나옵니다.


QueryFailedError: duplicate key value violates unique constraint "UQ_78a916df40e02a9deb1c4b75edb"

at new QueryFailedError (/Users/alexlee/Develop/practices/nestjs/nestjs-board-app/src/error/QueryFailedError.ts:11:9)

at PostgresQueryRunner.<anonymous> (/Users/alexlee/Develop/practices/nestjs/nestjs-board-app/src/driver/postgres/PostgresQueryRunner.ts:228:19)

at step (/Users/alexlee/Develop/practices/nestjs/nestjs-board-app/node_modules/tslib/tslib.js:144:27)

at Object.throw (/Users/alexlee/Develop/practices/nestjs/nestjs-board-app/node_modules/tslib/tslib.js:125:57)

at rejected (/Users/alexlee/Develop/practices/nestjs/nestjs-board-app/node_modules/tslib/tslib.js:116:69)

at processTicksAndRejections (node:internal/process/task_queues:95:5) {

length: 231,

severity: 'ERROR',

code: '23505',

detail: 'Key (username)=(alexlee) already exists.',


QueryFailedError 객체 타입인지 아닌지 비교하면 어떨까요?


try {

await this.save(user);

} catch (error) {

if (error instanceof QueryFailedError) {

throw new ConflictException('Existing username');

} else {

throw new InternalServerErrorException();

}

}


제가 해본 테스트에서는 잘 검출되네요.

이 강의 보시는 다른 분들께도 도움이 되길 바랍니다.

 

 

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
HenaPapa님의 프로필 이미지
HenaPapa

작성한 질문수

질문하기