Ask any question about JavaScript here... and get an instant response.
How can I create a custom error type to handle specific network failures in a try/catch block in JavaScript?
Asked on Nov 27, 2025
Answer
To create a custom error type in JavaScript for handling specific network failures, you can extend the built-in Error class. This allows you to throw and catch instances of your custom error type in a try/catch block.
<!-- BEGIN COPY / PASTE -->
class NetworkError extends Error {
constructor(message) {
super(message);
this.name = "NetworkError";
}
}
try {
// Simulate a network failure
throw new NetworkError("Failed to fetch data from the server.");
} catch (error) {
if (error instanceof NetworkError) {
console.error("Network error occurred:", error.message);
} else {
console.error("An unexpected error occurred:", error);
}
}
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "NetworkError" class extends the built-in "Error" class.
- The constructor sets the error message and assigns a custom name to the error type.
- In the try block, a "NetworkError" is thrown to simulate a network failure.
- The catch block checks if the error is an instance of "NetworkError" to handle it specifically.
- This approach helps in distinguishing between different types of errors in your application.
Recommended Links:
