DEV Community

artydev
artydev

Posted on

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

Top comments (0)