강의

멘토링

커뮤니티

Inflearn コミュニティ Q&A

geunhee02123438 のプロフィール画像
geunhee02123438

投稿した質問数

[リニューアル]タイプスクリプトオールインワン:Part2。実戦分析編

AxiosErrorとunknown errorの対処方法

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

作成

·

376

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의 대해서 타입이 좁혀지긴 하지만, 지저분해서 맞는 방법인지 모르겠네요

typescript

回答 1

1

zerocho님의 프로필 이미지
zerocho
インストラクター

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

geuni님의 프로필 이미지
geuni
質問者

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

감사합니다 ㅎㅎ

geunhee02123438 のプロフィール画像
geunhee02123438

投稿した質問数

質問する