Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Check `response.ok` Before Trusting a Fetch Response Body
A fetch wrapper that never checks `response.ok` will happily parse and return an error payload as if it succeeded.
Bad example
| 1 | export const patchCategory = async (id: number, categoryId: number): Promise<Category> => { |
| 2 | const response = await fetch(`/api/category`, { |
| 3 | method: 'PATCH', |
| 4 | headers: { 'Content-Type': 'application/json' }, |
| 5 | body: JSON.stringify({ id, categoryId }), |
| 6 | }); |
| 7 |
|
| 8 | return response.json(); |
| 9 | }; |
Explanation (EN)
Parses and returns the response body regardless of HTTP status, so a 4xx/5xx error response gets silently treated as a successful `Category`, hiding failures from the caller.
Objašnjenje (HR)
Parsira i vraća tijelo odgovora bez obzira na HTTP status, pa se 4xx/5xx odgovor s greškom tiho tretira kao uspješan `Category`, skrivajući neuspjeh od pozivatelja.
Good example
| 1 | export const patchCategory = async (id: number, categoryId: number): Promise<Category> => { |
| 2 | const response = await fetch(`/api/category`, { |
| 3 | method: 'PATCH', |
| 4 | headers: { 'Content-Type': 'application/json' }, |
| 5 | body: JSON.stringify({ id, categoryId }), |
| 6 | }); |
| 7 |
|
| 8 | if (!response.ok) { |
| 9 | throw new Error(`Failed to update category: ${response.status}`); |
| 10 | } |
| 11 |
|
| 12 | return response.json(); |
| 13 | }; |
Explanation (EN)
Checks `response.ok` before parsing the body and throws with the status code on failure, so callers can distinguish a real success from an error response.
Objašnjenje (HR)
Provjerava `response.ok` prije parsiranja tijela i baca grešku sa statusnim kodom u slučaju neuspjeha, tako da pozivatelji mogu razlikovati stvarni uspjeh od odgovora s greškom.