programing

오류 처리 방법 fetch()의 비동기/대기

starjava 2023. 4. 2. 09:39
반응형

오류 처리 방법 fetch()의 비동기/대기

리액트 앱에 스트라이프 비동기 코드가 있어 코드에 오류 처리를 추가하려고 하는데 어떻게 처리해야 할지 모르겠다. .then()으로 하는 방법은 알지만 비동기/ait는 처음입니다.

편집필

응답 탭의 네트워크 탭에서 오류가 발생했는데 콘솔에 기록할 수 있습니까?

    submit = async () => {
    const { email, price, name, phone, city, street, country } = this.state;
    let { token } = await this.props.stripe
      .createToken({
        name,
        address_city: city,
        address_line1: street,
        address_country: country
      })
      .catch(err => {
        console.log(err.response.data);
      });

    const data = {
      token: token.id,
      email,
      price,
      name,
      phone,
      city,
      street,
      country
    };

    let response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).catch(err => {
      console.log(err.response.data);
    });
    console.log(response);
    if (response.ok)
      this.setState({
        complete: true
      });
  };

감사해요.

Fetch는 네트워크 오류만 검출합니다.기타 오류(401, 400, 500)는 수동으로 검출하여 거부해야 합니다.

await fetch("/charge/pay", headers).then((response) => {
    if (response.status >= 400 && response.status < 600) {
      throw new Error("Bad response from server");
    }
    return response;
}).then((returnedResponse) => {
   // Your response to manipulate
   this.setState({
     complete: true
   });
}).catch((error) => {
  // Your error is here!
  console.log(error)
});

이러한 취득 제한에 익숙하지 않은 경우는, Axios 를 사용해 주세요.

var handleError = function (err) {
    console.warn(err);
    return new Response(JSON.stringify({
        code: 400,
        message: 'Stupid network Error'
    }));
};

var getPost = async function () {

    // Get the post data
    var post = await (fetch('https://jsonplaceholder.typicode.com/posts/5').catch(handleError));

    // Get the author
    var response = await (fetch('https://jsonplaceholder.typicode.com/users/' + post.userId).catch(handleError));

       if (response.ok) {
            return response.json();
        } else {
            return Promise.reject(response);
        }

};

다음 중 하나를 사용할 수 있습니다.try/catch일반적인 필수 프로그래밍과 마찬가지로

try {
    let response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    });
} catch(error) {
    // Error handling here!
}

또는 믹스 앤 매치를 할 수도 있습니다..catch()약속할 때처럼 말이야

let response = await fetch("/charge/pay", {
    method: "POST",
    headers: {
       "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
}).catch(function(error) {
    // Error handling here!
});

트라이캐치로 대기시간을 마무리하세요.

try {
    let response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    });

    console.log(response);
} catch (error) {
    console.log(error);
}

이것은 서버가 반환된 경우 작동합니다.{ message: "some error" }하지만 난 그걸 지지하려고 노력중이야res.statusText또, 다음과 같습니다.

        const path = '/api/1/users/me';
        const opts = {};
        const headers = {};
        const body = JSON.stringify({});
        const token = localStorage.getItem('token');

        if (token) {
          headers.Authorization = `Bearer ${token}`;
        }

        try {
            const res = await fetch(path, {
                method: opts.method || 'GET',
                body,
                headers
            });

            if (res.ok) {
                return await (opts.raw ? res.text() : res.json());
            }

            const err = await res.json();

            throw new Error(err.message || err.statusText);
        } catch (err) {
            throw new Error(err);
        }
 async function loginWithRedirect(payload: {
        username: string;
        password: string;
    }) {
      const resp = await (await fetch(`${env.API_URL}/api/auth/login`, {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(payload),
        credentials: "include",
      })).json();
      if (resp.error) {
        dispatch({type: "ERROR", payload: resp.error.message});
      } else {
        dispatch({type: "LOGIN", payload: resp});
      }
    }

response.ok가 false일 경우 다음과 같이 함수를 호출한 후 오류를 발생시키고 chain catch 메서드를 호출할 수 있습니다.

async function fetchData(){
    const response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    });

    if(!response.ok){
        const message = `An error occured: ${response.status}`;
        throw new Error(message);
    }
    
    const data = await response.json();
    return data;
}

fetchData()
    .catch(err => console.log(err.message));

fetch in async wait 를 사용하는 약속 함수를 씁니다.

const promisyFetch = (url, options) =>
new Promise((resolve, reject) => {
fetch(url, options)
  .then((response) => response.text())
  .then((result) => resolve(result))
  .catch((error) => reject(error));
});

그런데 try catch로 비동기적으로 쉽게 사용할 수 있습니다.

const foo = async()=>{
try {
    const result = await promisyFetch('url' requestOptions)
    console.log(result)
} catch (error) {
    console.log(error)
}
}

간단한 예시로 Promisy를 커스터마이즈할 수 있습니다.원하는 대로 함수를 가져오고 옵션을 요청합니다.

 const data = {
        token: token.id,
        email,
        price,
        name,
        phone,
        city,
        street,
        country
      };
      axios
        .post("/charge/pay", data)
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err.response.data);
        });

언급URL : https://stackoverflow.com/questions/54163952/async-await-in-fetch-how-to-handle-errors

반응형