Blog>
Snippets

Network Error Wrapper

Construct a NetworkError class that captures issues related to network communications, like failed fetch requests due to network outages.
class NetworkError extends Error {
  constructor(message) {
    // Calls the constructor of the parent Error class.
    super(message);

    // Maintains proper stack trace for where our error was thrown (only available on V8).
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, NetworkError);
    }

    // A name specific to this class, useful for checking the error type.
    this.name = 'NetworkError';
  }
}
This code defines the NetworkError class, a subclass of the JavaScript Error class, which is specifically intended to represent errors related to network operations. It captures a message and sets the error name to 'NetworkError'. Additionally, it ensures that the stack trace is captured correctly in V8-based environments (like Chrome and Node.js).
async function fetchData(url) {
  try {
    // Attempt to fetch data from the provided URL.
    const response = await fetch(url);
    if (!response.ok) {
      // If the response status is not successful, throw a network error.
      throw new NetworkError(`Network Error: The request failed with status ${response.status}`);
    }
    return await response.json(); // Parse and return the response data as JSON.
  } catch (error) {
    if (error instanceof NetworkError) {
      // Handle NetworkError instances specifically.
      console.error(error.message);
    } else {
      // Handle other types of errors that may occur.
      console.error('An unexpected error occurred:', error);
    }
    // Re-throw the error for further handling if necessary.
    throw error;
  }
}
This code snippet provides an example of using the NetworkError class within an async function, named fetchData, which is responsible for fetching data from a given URL using the Fetch API. It handles unsuccessful network requests by throwing a NetworkError with an appropriate message. It also demonstrates how to catch and handle these errors, distinguishing them from other types of JavaScript errors.