index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. ]);
  13. export default function isNetworkError(error) {
  14. const isValid = error
  15. && isError(error)
  16. && error.name === 'TypeError'
  17. && typeof error.message === 'string';
  18. if (!isValid) {
  19. return false;
  20. }
  21. const {message, stack} = error;
  22. // Safari 17+ has generic message but no stack for network errors
  23. if (message === 'Load failed') {
  24. return stack === undefined
  25. // Sentry adds its own stack trace to the fetch error, so also check for that
  26. || '__sentry_captured__' in error;
  27. }
  28. // Deno network errors start with specific text
  29. if (message.startsWith('error sending request for url')) {
  30. return true;
  31. }
  32. // Standard network error messages
  33. return errorMessages.has(message);
  34. }