Async/Await in fetch() how to handle errors Async/Await in fetch() how to handle errors reactjs reactjs

Async/Await in fetch() how to handle errors


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.


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


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!}

Or you can mix-and-match .catch() just like you do with promises:

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