index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const objectToString = Object.prototype.toString;
  2. const isError = value => objectToString.call(value) === '[object Error]';
  3. const errorMessages = new Set([
  4. 'network error', // Chrome
  5. 'Failed to fetch', // Chrome
  6. 'NetworkError when attempting to fetch resource.', // Firefox
  7. 'The Internet connection appears to be offline.', // Safari 16
  8. 'Network request failed', // `cross-fetch`
  9. 'fetch failed', // Undici (Node.js)
  10. 'terminated', // Undici (Node.js)
  11. ' A network error occurred.', // Bun (WebKit)
  12. 'Network connection lost', // Cloudflare Workers (fetch)
  13. ]);
  14. export default function isNetworkError(error) {
  15. const isValid = error
  16. && isError(error)
  17. && error.name === 'TypeError'
  18. && typeof error.message === 'string';
  19. if (!isValid) {
  20. return false;
  21. }
  22. const {message, stack} = error;
  23. // Safari 17+ has generic message but no stack for network errors
  24. if (message === 'Load failed') {
  25. return stack === undefined
  26. // Sentry adds its own stack trace to the fetch error, so also check for that
  27. || '__sentry_captured__' in error;
  28. }
  29. // Deno network errors start with specific text
  30. if (message.startsWith('error sending request for url')) {
  31. return true;
  32. }
  33. // Standard network error messages
  34. return errorMessages.has(message);
  35. }