서버에 데이터가 없을 때 예외처리 하는 법

piper ·2024년 2월 16일
0

React

목록 보기
10/22

서버에 데이터가 없을 때 예외처리하는 법에 대해 공부해보려고 한다.
먼저 기본적인 try와 catch 문부터 복습해보았다.

const datas = { age: 34 };

try {
  let user = JSON.stringify(datas);
  let jsonUser = JSON.parse(user);
  console.log(jsonUser);
  if (!jsonUser.name) {
    throw new SyntaxError("불완전한 데이터: 이름없음");
  }
  console.log(user.name);
} catch (e) {
  console.log("JSON Error" + e.message);
}

datas라는 객체를 json형식의 객체로 바꾸어 주고

let user = JSON.stringify(datas); ----> 문자열로
let jsonUser = JSON.parse(user); ....> JSON 객체로

name이 없기 때문에 try문은 SyntaxError를 보내며 종료가 되고
console에는
{ age: 34 }
JSON Error 불완전한 데이터: 이름없음 이라고 찍히며 종료된다.

이와 같이 서버로부터 데이터를 받아오지 못하는 경우에 대한 예외 처리 역시
'try-catch' 문을 사용해서 에러를 처리할 수 있다.
스타워즈 api를 통해서 데이터를 불러와보는 연습을 하겠다.

연습중 발생한 에러
1) useEffect를 써서 데이터를 불러오는 함수를 만들고나서 마지막에 해당 함수를
호출해 주는 것을 잊지 않도록 한다.
2) response.json() 메서드 역시 promise을 반환하기 때문에
앞에 await를 써줘야 한다.
3) Objects are not valid as a React child.
(found: object with keys {키1,키2}).
If you meant to render a collection of children, use an array instead.
=> Object 타입을 렌더링할 때는 타입을 지켜야 한다.
이를 수정할 수 있는 방법은 JSON 데이터를 문자열화 시켜주는 것이다.
JSX문에 JSON.stringify()를 써주면 된다.

이를 다 수정해준 뒤의 코드:

import React from "react";
import { useEffect, useState } from "react";

const Error = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchedData = async () => {
      try {
        const response = await fetch("https://swapi.dev/api/people/1/");

        if (!response.ok) {
          throw new Error("서버로부터 가져오기 실패");
        } else {
          const result = await response.json();
          console.log(result);
          setData(result);
        }
      } catch (error) {
        setError(error.message);
      }
    };

    fetchedData();
  }, []);

  return (
    <div>
      <h2>에러테스트</h2>
      {data ? <p>{JSON.stringify(data)}</p> : <p>에러:{error}</p>}
    </div>
  );
};

export default Error;

profile
연습일지

0개의 댓글