fetch — Detect Network Error

We’re building a Vue.js application for a client project. This Vue.js app uses the useFetch composable from VueUse. This composable uses the browser’s fetch to send requests to a given URL and handle the responses.

We wanted to integrate handling in the Vue.js app to detect network errors. The user should notice that something is wrong when requests don’t go through to the backend (for whatever reason).

This tutorial shows you how to detect network errors when using the native fetch function in a browser.

JavaScript Series Overview

Detect a Network Error When Using Fetch

There isn’t an error with a message like “network error” when using fetch. A network error depends on your browser. The error thrown when a request doesn’t succeed has a different error message across the browsers.

Here are some examples from common browsers for error messages when a network error occurs:

// Chrome
'network error'  
'Failed to fetch'

// Firefox
'NetworkError when attempting to fetch resource.'

 // Safari 16
'The Internet connection appears to be offline.'

 // Safari 17+
'Load failed'  

That means you should check whether a given fetch error has one of the possible error messages. You can imagine that this leaves room for failure because browser companies can come up with new or changed error messages in the future.

There’s the is-network-error package from Sindre Sorhus that could be a usable option for you.

Detecting a Network Error with the useFetch Vue.js Composable

We’re using the useFetch composable from VueUse in one of our projects. The useFetch composable supports an onFetchError hook. This hook receives the request context as an argument. The request context contains the details about the response.

The response is null or undefined in situations when the request doesn’t have one. You can then check ctx.error for error details. In case of network errors, you’re likely finding one of the above-mentioned error messages:

const { data, error } = useFetch(url, {  
  onFetchError(ctx) {
    if (ctx.response == null) {
      // potentially a server error. Check `ctx.error` for details
    }

    return ctx
  },
})

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.