Course contentsShow
← Web Development
Lesson 1495 of 2,98227. REST API Design for FrontendFree lesson

Handling Unexpected Status Codes

Build resilient frontend code that gracefully handles status codes outside the expected range.

Handling Unexpected Status Codes

You'll learn how to write frontend code that doesn't break when the API returns status codes you didn't anticipate.

When building applications that consume REST APIs, you've learned about standard status codes like 200 OK, 404 Not Found, and 500 Internal Server Error. But what happens when your API returns a status code you didn't plan for? Maybe the server returns 418 I'm a teapot (yes, that's real), 507 Insufficient Storage, or a future status code that doesn't exist yet. Brittle code that only checks for expected codes will fail silently or crash.

Resilient handling means using ranges, not exact matches:

Instead of checking every possible status code individually, use range-based logic:

  • 200-299: Success (covers all 2xx codes)
  • 300-399: Redirection (covers all 3xx codes)
  • 400-499: Client errors (covers all 4xx codes)
  • 500-599: Server errors (covers all 5xx codes)

This approach means your code gracefully handles any status code within a category, even ones you've never seen before.

Always include a fallback:

Even with range checking, have a default handler for completely unexpected responses. Maybe the server is misconfigured and returns invalid codes, or network middleware modifies the response. Your fallback should log the unexpected code, show a generic error message to users, and prevent application crashes.

The analogy: Think of status code handling like preparing for weather. You pack for sunny, rainy, and cold conditions (expected ranges), but you also bring a Swiss Army knife for anything unexpected. You won't predict every scenario, but you'll survive it.

Key Takeaway:
Handle status codes by checking ranges (2xx, 4xx, 5xx) rather than exact values, and always include a fallback for truly unexpected responses to keep your frontend resilient.