Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await in fetch() how to handle errors

I have stripe async code in my React app, and trying to add error handling in my code but have no idea how to handle it. i know how to do it with .then() but async/await is new to me

EDITED

added .catch() i got errors in network tab in response tab. but i can log it to console?

    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       });   }; 

thanks

like image 958
Exc Avatar asked Jan 12 '19 21:01

Exc


People also ask

How do you handle errors in await fetch?

You can either use try / catch just like normal, imperative programming: try { let response = await fetch("/charge/pay", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON. stringify(data) }); } catch(error) { // Error handling here! } Wrap your await with try catch.

Does fetch support async-await?

async/await syntax fits great with fetch() because it simplifies the work with promises.

Does fetch throw error?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.


1 Answers

Fetch detects only network errors. Other errors (401, 400, 500) should be manually caught and rejected.

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) });  

If you are not comfortable with this limitation of fetch, try using axios.

like image 182
Avanthika Avatar answered Sep 25 '22 22:09

Avanthika