Axios Instance 생성하기
api를 보면 token이 필요한 경우와 불필요한 경우가 있습니다. 처음에는 instance를 두개 생성해서 하나는 토큰이 있는 경우, 토큰이 없는 경우로 나눠서 구현하려했으나 이 과정도 하나의 인스턴스로 관리할 수 있을 것 같아 다음과 같이 구현했습니다.
custom config를 추가할 수 있는 방법은 다음 사이트를 참고했습니다.
authorization
이라는 custom config를 생성하여 기본값은 true
로 설정했습니다. export const axiosInstance = axios.create({ baseURL: import.meta.env.VITE_BASE_URL, authorization: true, });
index.d.ts
custom config를 추가했기때문에 Axios 라이브러리에 사용자 정의 설정을 추가해야합니다. axios 모듈을 확장하는 구문
declare module “axios”
를 작성하고, AxiosRequestConfig
인터페이스에 사용자 정의 필드인 authorization
을 추가했습니다. import "axios"; declare module "axios" { export interface AxiosRequestConfig { authorization?: boolean; } }
request interceptor
instance에서 생성한 custom config authorization 값에 따라, true인 경우 토큰을 헤더로 사용했습니다.
axiosInstance.interceptors.request.use((config) => { if (!config.authorization) return config; const token = getStorage(ACCESS_TOKEN_KEY); if (!token) { throw new Error('토큰이 유효하지 않습니다'); } config.headers.Authorization = `Bearer ${token}`; return config; });
Custom Error Code
서버에서 에러에 대한 메세지를 보내주지만, 바로 사용자에게 보여주는 것은 좋은 에러 메세지가 아니라고 생각했습니다. 따라서 클라이언트 측에서 사용할 에러 메세지를 별도로 관리하는 방법을 생각했습니다.
다만 현재 서버에서는
custom error code
를 전송해주고 있지않아 에러메세지를 좋은 에러 메세지로 변환하는 작업을 하는게 좋을지, 클라이언트 측에서 유효성 검사를 하여 에러 메세지를 출력하는 방식이 좋을지에 대한 고민을 했습니다.
단점: 에러 메세지에 대한 정보가 없어, 우리가 직접 다양한 시도를 통해 에러 메세지를 정리해야함.
/constants/api.ts
// 출력되는 에레메세지를 key값으로 value값을 에러 메세지를 지정해주면 됩니다! export const ERROR_MESSAGE = { "Your email and password combination does not match an account.": '등록되지 않은 아이디이거나 아이디 또는 비밀번호를 잘못 입력했습니다' };
errormessage를 작성하기 전에 에러 메세지는
default error message
로 토스트가 출력됩니다.Custom Error & Error 확장
throw new Error는 오류 메세지 하나만 전달할 수 있어 커스텀 에러 객체를 생성하면 Error 객체를 확장할 수 있습니다.
export class HTTPError extends Error { statusCode: number; constructor(statusCode: number, message?: string) { super(message); this.name = "HttpError"; this.statusCode = statusCode; Object.setPrototypeOf(this, HTTPError.prototype); } }
개발 과정에서 편의를 위해
response interceptor
에 console.log()
를 추가했습니다! console.log(statusCode, message, customMessage); console.log(error);
에러 메세지 관련 사이트
관련해서 더 좋은 방법이 있다면 공유해주시면 반영하겠습니다 ㅎㅎ