Typescript로 커스텀 에러 정의 및 사용하기
에러 정의를 “커스텀화”해서 얻고 싶은 것
- return 되는 값의 형식을 통일화
- return 되는 값들의 타입 제공 및 구분 가능
- 로직 내에서 손 쉽게 에러 발생 시키기 (추상화)
1. 에러 정의
- 아래와 같이 ERROR 를 정의했으며, 모든 api 의 에러 응답은 다음의 형식을 갖춘다.
1
2
3
4
5
6
export interface ERROR {
result: false;
code: string;
httpStatus: number;
data: string; // error Message or data
}
- 예시로 다음은 EMAIL이 존재하지 않았을 때의 Error 이다.
1
2
3
4
5
6
export interface EMAIL_NOT_EXIST extends ERROR {
result: false;
code: ErrorCodeEnum.EMAIL_NOT_EXIST;
httpStatus: 404;
data: "해당 메일이 존재하지 않습니다.";
}
- 해당 인터페이스는 ERROR의 형식을 그대로 따른다.
2. Exception 발생 시키기
- 서비스 로직 내에서 에러를 보통 다음과 같이 발생시킨다.
1
throw new NotFoundException();
NotFoundException
은 exception에 관한 class 이며,HttpException
을 상속받는다.- 따라서 new 생성자로 발생시킬 수 있다.
- 그렇지만 우리는 interface로 구현되어 있어 이를 호출하는 곳에서 생성하기 어렵다.
- 따라서 이는
typia.random<T>()
으로 다음과 같이 생성시킬 수 있다.
1
2
3
4
5
6
// custom exception 객체
export class Exception extends HttpException {
constructor(error: ERROR) {
super(error, error.httpStatus);
}
}
1
2
// 호출하는 쪽
throw new Exception(typia.random<EMAIL_NOT_EXIST>())
- 이러면 typia가 EMAIL_NOT_EXIST라는 interface에 맞게 구현체를 생성하고, Exception에 넣어 HttpException을 발생시킨다.
문제점
- typia.random 은 runtime에 에러를 랜덤 생성시킨다. 이는 성능 문제가 없을까?
- 사실 에러들은 하나의 객체일텐데, 이를 굳이 매번 생성시키지 말고, singleton 으로 구현하면 성능이 좋지 않을까?
3. Singleton Exceptions
- 다음과 같이 runtime이 아닌 실행 시간에 singleton 으로 에러 객체를 생성해두는 것으로 개선했다.
1
2
3
4
5
6
7
8
9
10
export const ExceptionList = {
MAIL_ALREADY_EXIST: new Exception(typia.random<MAIL_ALREADY_EXIST>()),
NICKNAME_ALREADY_EXIST : new Exception(typia.random<NICKNAME_ALREADY_EXIST>()),
MOONJIN_EMAIL_ALREADY_EXIST : new Exception(typia.random<MOONJIN_EMAIL_ALREADY_EXIST>()),
SIGNUP_ERROR : new Exception(typia.random<SIGNUP_ERROR>()),
WRITER_SIGNUP_ERROR : new Exception(typia.random<WRITER_SIGNUP_ERROR>()),
EMAIL_NOT_EXIST : new Exception(typia.random<EMAIL_NOT_EXIST>()),
TOKEN_NOT_FOUND : new Exception(typia.random<TOKEN_NOT_FOUND>()),
INVALID_TOKEN : new Exception(typia.random<INVALID_TOKEN>())
}
1
2
// 호출하는 쪽
throw ExceptionList.EMAIL_NOT_EXIST;
- 에러를 발생시키는 쪽에서도 한결 간결해진 것 같은 기분이다.