🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Error Handling & Status Codes

Learn how to build robust safety nets around your network requests. Master try/catch blocks, understand HTTP Status Codes, and learn how to bypass the native limitations of the Fetch API.

Narrated Video Summary
data-composition-id="apicreationmanipulation-module2_lesson6"1280×720 @ 30fps5 clips2:28 total

Handling Network Failures

You now know how to execute `fetch()` requests. However, the internet is an inherently chaotic environment. Servers crash, databases lock up, and users lose Wi-Fi connections in tunnels. If you do not handle these errors, your application will freeze and the user will stare at a blank screen. Professional Frontend Developers design architectures that gracefully handle failure before they even write the success logic.

// 🚨 The Naive Fetch
// If the server is offline, this crashes the app.
const data = await fetch("/users").then(r => r.json());

// Objective: We must build safety nets.

The try/catch Block

The primary safety net for asynchronous JavaScript is the `try/catch` block. You place your risky `await fetch()` code inside the `try` block. If the browser physically cannot reach the server (e.g., the user turned on Airplane Mode), the Promise rejects. JavaScript immediately stops executing the `try` block and jumps into the `catch` block, where you can safely display a 'Check your connection' message to the user.

// 🛡️ The try/catch Safety Net

try {
  const response = await fetch("https://api.com/data");
  // Success logic here...
} catch (error) {
  // Triggers ONLY on complete network failure
  showErrorToUser("You are offline.");
}

The 404 Trap

The biggest trap in the Fetch API is HTTP status codes. If the server is online, but you request a user that does not exist, the server will return a `404 Not Found` response. Crucially, `fetch` DOES NOT view a 404 as an error! The network request was successful (the server replied). Therefore, the Promise resolves, and the `catch` block is bypassed. If you try to run `.json()` on a 404 HTML error page, your app will crash.

// 🪤 The Fetch Trap

try {
  // Server returns 404 Not Found
  const res = await fetch("/bad-url");
  // This throws an error because 404s aren't JSON!
  const data = await res.json(); 
} catch (error) {
  console.log("Caught it!");
}

Response.ok

To fix the 404 trap, you must manually inspect the HTTP response before calling `.json()`. The Response object has a built-in property called `response.ok`. This property is simply a boolean that is `true` if the HTTP status code is between 200 and 299 (success), and `false` if it is 400 or 500 (error). If `!response.ok` is true, you must manually `throw` an error to force execution into the `catch` block.

// ✅ The Professional Fetch Pattern

try {
  const res = await fetch("/users");
  
  if (!res.ok) {
    throw new Error(`HTTP Error: ${res.status}`);
  }
  
  const data = await res.json();
} catch (error) {
  console.error(error.message);
}

Robust Architecture

By combining `try/catch` with manual `response.ok` checks, you have built an unbreakable safety net. If the user's internet drops, the `catch` block handles it. If the server crashes and returns a 500 error, your manual throw forces the `catch` block to handle it. You are now ready to handle real-world API consumption. Next, we will discuss how to secure these requests with Authentication.

/* Error Handling Complete */
.safety { next: 'api_authentication'; }
0:00 / 2:28
Scene 1 / 5 — Handling Network Failures
Total XP: 0|💻 apicreationmanipulation XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Error Handling

Manage chaos.

Quick Quiz //

Which of the following describes the proper use of a `try/catch` block with network requests?


🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Happy path programming is for tutorials. Real-world applications live in a chaotic network environment. You must engineer your code to fail gracefully.

1The Inevitability of Failure

When building web applications, you must assume the network will fail. The user might drive through a tunnel. The server might run out of memory. The DNS might go down. If your fetch request is not wrapped in a try/catch block, an unhandled Promise rejection will bubble up to the top of the runtime environment, often causing a fatal crash or leaving the UI permanently stuck in a 'Loading...' state.

+
// The try/catch Safety Net

try {
  const response = await fetch("https://api.com/data");
  // Success logic here...
} catch (error) {
  // Triggers ONLY on complete network failure
  showErrorToUser("You are offline.");
}
localhost:3000
localhost:3000
Graceful Degradation: Network drop intercepted by catch block. UI remains stable.

2The Quirks of Fetch

One of the most confusing aspects of the Fetch API is its definition of 'success'. To fetch, a successful request simply means that a response was received from a server. It doesn't care if that response is a 200 OK (Here is your data) or a 500 Internal Server Error (The database exploded). Because a response was received, the Promise resolves. This is why you must ALWAYS manually check response.ok before attempting to parse the JSON.

+
// The Professional Fetch Pattern

try {
  const res = await fetch("/users");
  if (!res.ok) {
    throw new Error(`HTTP Error: ${res.status}`);
  }
  const data = await res.json();
} catch (error) {
  console.error(error.message);
}
localhost:3000
localhost:3000
Manual Verification: Explicit check forces HTTP errors into the catch block.

3Decoding Status Codes

As a developer, you must memorize the three primary HTTP status code ranges. 200-level codes represent Success (e.g., 200 OK, 201 Created). 400-level codes represent Client Errors (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found). This means the client messed up the request. 500-level codes represent Server Errors (e.g., 500 Internal Error, 503 Service Unavailable). This means the client's request was fine, but the server crashed.

+
// Common HTTP Status Ranges

200 - 299 -> Success
400 - 499 -> Client Error (Your fault)
500 - 599 -> Server Error (Their fault)
localhost:3000
localhost:3000
Status decoded: Backend response efficiently classified by standard HTTP ranges.

4Step-by-Step Breakdown

Handling Network Failures. You now know how to execute fetch() requests. However, the internet is an inherently chaotic environment. Servers crash, databases lock up, and users lose Wi-Fi connections in tunnels. If you do not handle these errors, your application will freeze and the user will stare at a blank screen. Professional Frontend Developers design architectures that gracefully handle failure before they even write the success logic.

The try/catch Block. The primary safety net for asynchronous JavaScript is the try/catch block. You place your risky await fetch() code inside the try block. If the browser physically cannot reach the server (e.g., the user turned on Airplane Mode), the Promise rejects. JavaScript immediately stops executing the try block and jumps into the catch block, where you can safely display a 'Check your connection' message to the user.

When dealing with fetch(), in what specific scenario will the catch block execute?

  • When there is a physical network failure (like the user losing their Wi-Fi connection) and the request cannot even reach the server.
  • When the server returns a 404 Not Found error.

The 404 Trap. The biggest trap in the Fetch API is HTTP status codes. If the server is online, but you request a user that does not exist, the server will return a 404 Not Found response. Crucially, fetch DOES NOT view a 404 as an error! The network request was successful (the server replied). Therefore, the Promise resolves, and the catch block is bypassed. If you try to run .json() on a 404 HTML error page, your app will crash.

Response.ok. To fix the 404 trap, you must manually inspect the HTTP response before calling .json(). The Response object has a built-in property called response.ok. This property is simply a boolean that is true if the HTTP status code is between 200 and 299 (success), and false if it is 400 or 500 (error). If !response.ok is true, you must manually throw an error to force execution into the catch block.

Because fetch() does not automatically reject Promises for 404 or 500 HTTP errors, what must you manually do immediately after awaiting the fetch call?

  • Immediately call .json() on the response.
  • Check if response.ok is true; if it's false, manually throw an Error so the catch block can handle it.

Robust Architecture. By combining try/catch with manual response.ok checks, you have built an unbreakable safety net. If the user's internet drops, the catch block handles it. If the server crashes and returns a 500 error, your manual throw forces the catch block to handle it. You are now ready to handle real-world API consumption. Next, we will discuss how to secure these requests with Authentication.

Level Up 🚀

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Semantic Usage

Using the proper structure for Handling Network Failures ensures that screen readers can correctly interpret the content hierarchy and purpose.

<!-- Apply semantic elements appropriately -->

SEO Implications

  • 1

    Contextual Relevance

    Proper implementation of Handling Network Failures provides search engine crawlers with better context, improving the indexing accuracy of your page.

Best Practices

Clean Code

Always validate your structure when using Handling Network Failures to prevent layout shifts and DOM inconsistencies.

Separation of Concerns

Keep styling and behavior separate from the structural markup of Handling Network Failures.

Frequent Bugs

THE BUG

Unexpected layout shifts or styling failures.

THE FIX

Ensure all implementations related to Handling Network Failures are properly structured according to strict specifications.

Real-World Examples

Production Usage

Here is how Handling Network Failures is typically implemented in a professional, robust application.

<!-- Best practice implementation of Handling Network Failures -->
<div class="production-ready">
  <!-- Content -->
</div>

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Not reading error messages carefully

Uncaught TypeError: Cannot read properties of undefined (reading 'length') // Solution: Ensure the variable you are calling .length on is initialized as a string or an array, not undefined.

The Solution //

Most of the time, the compiler or interpreter tells you exactly what line caused the crash and why. Read stack traces from the top down to identify the root cause.

The Error //

Hardcoding sensitive credentials

// Wrong const API_KEY = 'sk-123456789'; // Correct const API_KEY = process.env.API_KEY;

The Solution //

Never hardcode API keys, passwords, or secrets in your source code. Use environment variables (.env files) to keep them secure and out of version control.

Lesson Glossary

[01]try/catch

A programming construct used to handle exceptions (errors). Risky code goes in 'try', and the recovery logic goes in 'catch'.

Code Preview
The Safety Net

[02]response.ok

A read-only boolean property of the Fetch Response object indicating whether the HTTP status code was successful (200-299).

Code Preview
The Verification

[03]HTTP 404

A client error status code indicating that the server cannot find the requested resource (endpoint).

Code Preview
Not Found

[04]HTTP 500

A server error status code indicating that the server encountered an unexpected condition that prevented it from fulfilling the request.

Code Preview
Server Crash

[05]Graceful Degradation

The practice of building systems that continue to operate (or fail nicely, showing polite messages) when a component breaks.

Code Preview
The Soft Landing

Continue Learning