Verified Jobs Live
JavaScript & Web Technologies Medium Level ~3 min read

How should fetch code handle HTTP errors and malformed JSON?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
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.