-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
[자문자답] 디비 중복 오류 검출 방법 변경? QueryFailedError
22.09.23 12:06 작성 조회수 668
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();
}
}
제가 해본 테스트에서는 잘 검출되네요.
이 강의 보시는 다른 분들께도 도움이 되길 바랍니다.
답변을 작성해보세요.
답변 0