How should fetch code handle HTTP errors and malformed JSON?
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
fetch usually rejects for network failures, but it resolves for HTTP responses such as 404 or 500. Check response.ok or an expected status before treating the response as successful. JSON parsing can fail independently, and a 204 response may have no body. Preserve useful error context without displaying sensitive server details. Add cancellation or a timeout policy and decide whether retries are safe. The example assumes a successful endpoint retu s JSON; it deliberately throws for non-success status codes.
Related Questions in JavaScript & Web Technologies
Explain the JavaScript Event Loop, Call Stack, Microtask, and Macrotask Queues
Intermediate level • 425 views
What is a closure? Show a practical example.
Easy level • 1 views
What is the output of synchronous code, a resolved promise, and setTimeout with zero delay?
Medium level • 1 views
How do event bubbling and delegation help with a dynamic list of buttons?
Medium level • 1 views
A live-search page sometimes shows results for an older query. How would you fix it?
Medium level • 1 views