is-network-error.ts
This file
Path
source/utils/is-network-error.ts
46 lines · 1.5 KiB · TypeScript
Last changed by
Accept a cross-realm `beforeError` error and validate a `ky.retry({delay})`Sindre Sorhusbefore adoptionbd0e26f
History of this fileTake it
Fix handling of Safari errors with domainsSindre Sorhusbefore adoption61d6d66
line 1why, one step back1// Inlined from https://github.com/sindresorhus/is-network-error v1.3.2Accept a cross-realm `beforeError` error and validate a `ky.retry({delay})`Sindre Sorhusbefore adoptionbd0e26f
line 2why, one step back2import {isError} from './is.js';Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 3–27why, one step back34const errorMessages = new Set([5 'network error', // Chrome6 'NetworkError when attempting to fetch resource.', // Firefox7 'The Internet connection appears to be offline.', // Safari 168 'Network request failed', // `cross-fetch`9 'fetch failed', // Undici (Node.js)10 'terminated', // Undici (Node.js)11 ' A network error occurred.', // Bun (WebKit) - leading space is intentional12 'Network connection lost', // Cloudflare Workers (fetch)13]);1415export default function isRawNetworkError(error: unknown): error is TypeError {16 const isValid = error17 && isError(error)18 && error.name === 'TypeError'19 && typeof error.message === 'string';2021 if (!isValid) {22 return false;23 }2425 const {message, stack} = error;2627 // Safari 17+ has generic message but no stack for network errorsFix handling of Safari errors with domainsSindre Sorhusbefore adoption61d6d66
line 28why, one step back28 if (message === 'Load failed' || (message.startsWith('Load failed (') && message.endsWith(')'))) {Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 29–46why, one step back29 return stack === undefined30 // Sentry adds its own stack trace to the fetch error, so also check for that31 || '__sentry_captured__' in error;32 }3334 // Deno network errors start with specific text35 if (message.startsWith('error sending request for url')) {36 return true;37 }3839 // Chrome: exact "Failed to fetch" or with hostname: "Failed to fetch (example.com)"40 if (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {41 return true;42 }4344 // Standard network error messages45 return errorMessages.has(message);46}