JavaScript

js/fetch-check-ok

After fetch, check response.ok (or the status) before reading the body; fetch does not reject on 404 or 500.

umiarkowanastatycznefe-javascript

Dlaczego

fetch resolves for every HTTP answer, including 401, 404 and 500. Code that goes straight to res.json() then parses an error page, throws a confusing SyntaxError, or renders the error body as if it were data, and the user sees an empty list instead of an error message.

Poprawka

Check res.ok (or res.status) and throw an Error with the status when it is false; show an error state where the call is used. A shared helper (getJson(url)) that does this once is the simplest way to keep every call right; passing the response to such a helper counts as a check.

Przykłady

// bad
const users = await (await fetch('/api/users')).json()
// good
const res = await fetch('/api/users', { signal })
if (!res.ok) throw new Error(`GET /api/users failed: ${res.status}`)
const users = await res.json()

Źródła

Fakty

Identyfikator
js/fetch-check-ok
Waga
umiarkowana
Sprawdzanie
statyczne sprawdzane w kodzie źródłowym przez audit
Dotyczy plików
jsx html vue svelte astro
Uczy jej skill
fe-javascript JavaScript in the browser
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain js/fetch-check-ok