• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    해결됨

try catch 문에서 error handling 시에 'as' 대신 instance of 로 핸들링 할 수 있을까요?

23.04.03 00:00 작성 조회수 473

0

안녕하세요. 제로초님

try catch 문에서 error handling 시에 typescript의 as로 타입의 assertion 대신 아래와 같이 instanceof로 잡는 것은 좋을 방법인지 질문드립니다.

try {
      setLoading(true);
      const response = await axios.post('/user', {
        email,
        name,
        password,
      });
      Alert.alert('알림', '회원가입 완료');
    } catch (error) {
      if (error instanceof AxiosError) {
        Alert.alert(
          '네트워크 에러',
          error.response?.data.message ?? '알수없는 에러가 발생했습니다',
        );
      }
    } finally {
      setLoading(false);
    }

답변 1

답변을 작성해보세요.

1

instanceof로 해도 됩니다! axios에서는 if (axios.isAxiosError(error)) 라는 방식도 제공하고 있습니다.

elena님의 프로필

elena

질문자

2023.04.03

감사합니다 axios.isAxiosError 도 알아가겠습니다~