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
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.
async/await syntax fits great with fetch() because it simplifies the work with promises.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With