저번 글과 이어집니다.
저번에는 기본적인 HttpClient 만들기를했었다. 이어서 만들어보자
저번에 작성한 HttpClient를 보면 Response 설정 로직을 보면
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new Error(
errorData?.message ?? `HTTP error! status: ${response.status}`
);
}
가 있다.
이부분을 보면 response가 제대로 오지 않으면 에러를 던지는 구간이다. 그럼
throw new Error(
errorData?.message ?? `HTTP error! status: ${response.status}`
);
이 부분을 수정하면 에러를 일관되게 처리 할 수 있지 않을까?
그래서 에러를 일관되게 처리할 컴포넌트인 error.ts 파일을 만들고
new APIError(); 로 변경하자. 그리고 error.ts 파일을 작성해보자
// HttpClient.ts
const handleResponse = async <T>(response: Response, config: Config): Promise<T> => {
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new new APIError();
}
const data = await response.json();
return data as T;
};
이제 error.ts 파일을 작성해보자
내가 여기에 넣을 데이터는 총 4개이다.
1. 에러가 api에러인지 알려줄 것.
2. api 에러상태코드를 표기할 것.
3. api 보낼시 반환하는 에러 객체를 반환할 것.
4. 이전에 내가 보낸 데이터를 반환할 것.
이 네가지를 넣어야 한다.
이때 에러의 이름을 api 에러로 고정한다.
export class APIError extends Error {
readonly name = "APIError";
}
export class APIError extends Error {
readonly name = "APIError";
public readonly originalMessage: any;
constructor(
public status: number,
public data: any = null,
message: any
public readonly config?: any
)
const errorInfo = {
name: "APIError",
status: status,
message: message,
data: data,
};
Error 생성자는 문자열 메시지를 받아야 하므로, errorInfo 객체를 JSON 문자열로 변환해야한다.
이렇게 하면 에러를 출력했을 때 아래와 같이 나온다.
{"name":"APIError","status":404,"message":"Not Found","data":null}
this.originalMessage = message //
Object.setPrototypeOf(this, APIError.prototype);
*프로토 타입 체인을 재설정하는 이유
toJSON(): Record<string, unknown> {
return {
name: this.name,
status: this.status,
message: this.originalMessage,
data: this.data,
};
}
자이 이제 이렇게 만든걸 HttpClient 에 넣어주면 된다.
// HttpClient.ts
const handleResponse = async <T>(response: Response, config: Config): Promise<T> => {
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new new APIError(
response.status,
config.body || null,
errorData?.message || `Error ${response.status}`,
config,);
}
const data = await response.json();
return data as T;
};