Detect Network Failures When Using Fetch from Aaron Bruce

artydev

artydev

Posted on November 15, 2020

Detect Network Failures When Using Fetch
from Aaron Bruce

Awesome article from Bruce : Detect Network Failures

Client Side Timeouts are not Optional

try {
  const response = await Promise.race([
    fetch(request),
    new Promise((_, reject) => setTimeout(
      () => reject(new Error('Timeout'),
      10000
    )),
  ]);
} catch (e) {
  if (error.message === 'Timeout') {
    // retry
  } else {
    throw e; // rethrow other unexpected errors
  }
}
Enter fullscreen mode Exit fullscreen mode

Fetch throws “Network request failed”

try {
  const response = await Promise.race([
    fetch(request),
    new Promise((_, reject) => setTimeout(
      () => reject(new Error('Timeout'),
      10000
    )),
  ]);
} catch (e) {
  if (error.message === 'Timeout' 
    || error.message === 'Network request failed') {
    // retry
  } else {
    throw e; // rethrow other unexpected errors
  }
}
Enter fullscreen mode Exit fullscreen mode

Fetch Resolves with an Empty Body

let response;try {
  response = await Promise.race([
    fetch(request),
    new Promise((_, reject) => setTimeout(
      () => reject(new Error('Timeout'),
      10000
    )),
  ]);
} catch (e) {
  if (error.message === 'Timeout' 
    || error.message === 'Network request failed') {
    // retry
  } else {
    throw e; // rethrow other unexpected errors
  }
}try {
  const body = await response.json();
} catch (e) {
  // just retry, even if it's a PUT request
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
artydev
artydev

Posted on November 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related