• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

axios catch 에서 error 타입에 대해 as 없이 이렇게 사용하면 어떨까요?

23.09.29 23:07 작성 조회수 185

0

interface IResponse<T = {}> {
  data: T;
  message: string;
}

interface IUser {
  id: string;
  email: string;
  name: string;
}

class CustomError<T> extends AxiosError<T> {
  constructor(...args: any[]) {
    super(...args);
  }

  static isCustomError<T>(value: any): value is CustomError<T> {
    return value instanceof CustomError<T>;

  }
}


axios.get('').then().catch((error: unknown) => {
  if (CustomError.isCustomError<IResponse<IUser>>(error)) {
    // console.error(
    //   (error as  AxiosError<{ message: string }>.response?.data.message)
    // )
    
    const errorMessage = error.response?.data.message;
  }
})

response의 대해서 타입이 좁혀지긴 하지만, 지저분해서 맞는 방법인지 모르겠네요

답변 1

답변을 작성해보세요.

1

axios는 이제 자체적으로 axios.isAxiosError 메서드를 제공합니다!

geuni님의 프로필

geuni

질문자

2023.09.30

axios.isAxiosError 사용해도 타입 좁혀지네요!

감사합니다 ㅎㅎ