Axios能否区分「发起请求时无网络」与「请求后断网」两种错误?
Great question! Let's tackle how to tell apart these two frustratingly similar network error scenarios in Axios—since that generic "Network Error" message is basically useless for debugging.
The Core Issue
First, let's set the record straight: theoretically, Axios should hint at the difference, but browser limitations with XMLHttpRequest (which Axios uses under the hood) often blur the lines. Both scenarios throw the same vague error because the browser's XHR API doesn't expose granular error codes directly to Axios in a consistent way across all browsers.
You mentioned the Axios docs note that error.request should be populated for the "request sent then network dropped" case—but in many browser environments, even the initial "no connection on request start" scenario might still have an error.request object (since the XHR instance is created before the request fails). That's why you're seeing identical error objects.
Practical Ways to Distinguish the Scenarios
1. Pre-Check Network Status with navigator.onLine
Before firing off your Axios request, you can check the browser's online status to quickly flag the "no connection at request start" case upfront:
async function fetchData(url) { // Check if we're offline before initiating the request if (!navigator.onLine) { return Promise.reject(new Error("Initial network connection unavailable (ERR_CONNECTION_REFUSED-like scenario)")); } try { const response = await axios.get(url); return response; } catch (error) { // If we're offline now but were online when starting, it's likely a mid-request disconnect if (!navigator.onLine) { console.error("Network disconnected during request (ERR_INTERNET_DISCONNECTED-like scenario)"); } else { // This is probably a connection refused, DNS failure, or other server-side network error console.error("Connection refused or server unreachable"); } throw error; } }
Note: navigator.onLine isn't 100% perfect—it only checks if the browser has a network connection, not if that connection can reach your server. For example, if you're connected to a router with no internet, it'll still return true. But it's a useful first check.
2. Track Network State Changes Over Time
By listening to the browser's online and offline events, you can correlate network state changes with the timing of your request:
let currentOnlineStatus = navigator.onLine; // Set up event listeners to track network state window.addEventListener('online', () => { currentOnlineStatus = true; }); window.addEventListener('offline', () => { currentOnlineStatus = false; }); async function makeAxiosRequest(url) { const requestStartedAt = Date.now(); const wasOnlineAtStart = currentOnlineStatus; try { return await axios.get(url); } catch (error) { const requestDuration = Date.now() - requestStartedAt; if (!currentOnlineStatus) { if (wasOnlineAtStart && requestDuration > 0) { // We were online when starting, but went offline mid-request console.error("Network dropped while request was in flight"); } else { // We were offline from the start console.error("No network connection when initiating request"); } } else { // Online now, so this is likely a connection refused or server error console.error("Connection refused or server unreachable"); } throw error; } }
3. Dig Into Browser-Specific Error Details
In some modern browsers, you can access the underlying error cause via error.cause (depending on your Axios version and browser support). For example, in Chrome, you might find the actual net::ERR_CONNECTION_REFUSED or net::ERR_INTERNET_DISCONNECTED code here:
try { await axios.get(url); } catch (error) { // Check for browser-specific error codes if (error.cause?.message.includes("ERR_CONNECTION_REFUSED")) { console.error("Connection refused (no server response)"); } else if (error.cause?.message.includes("ERR_INTERNET_DISCONNECTED")) { console.error("Internet disconnected mid-request"); } }
Keep in mind this isn't cross-browser consistent, so use it as a supplementary check rather than a primary method.
Limitations to Keep in Mind
- Browser XHR APIs don't always expose granular error details to JavaScript, so perfect differentiation isn't always possible.
navigator.onLinecan give false positives (connected to a network but no internet) or false negatives in rare cases.- Server-side network errors (like a firewall blocking the request) might look identical to "no connection" errors from the frontend's perspective.
内容的提问来源于stack exchange,提问作者Andy Neale

