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 directly and throw errors with status + context
fetch resolves to a Response (or throws), so don't optional-chain response?.ok; when !response.ok, throw an error that includes the status code, statusText, and the resource identifier.
Bad example
| 1 | const response = await fetch(new URL(`api/users/${id}`, baseUrl)); |
| 2 |
|
| 3 | if (!response?.ok) { |
| 4 | throw new Error('Error fetching user'); |
| 5 | } |
Explanation (EN)
The optional chaining on response?.ok is meaningless because fetch never resolves to null/undefined, and the error message gives no clue about which user failed or why.
Objašnjenje (HR)
Optional chaining na response?.ok je besmislen jer fetch nikad ne razrijesi u null/undefined, a poruka greske ne govori koji je korisnik pao niti zasto.
Good example
| 1 | const response = await fetch(new URL(`api/users/${id}`, baseUrl)); |
| 2 |
|
| 3 | if (!response.ok) { |
| 4 | throw new Error( |
| 5 | `Failed to fetch user ${id}: ${response.status} ${response.statusText}`, |
| 6 | ); |
| 7 | } |
Explanation (EN)
response.ok is accessed directly, and the thrown error carries the status code, statusText, and the id so failures are diagnosable from logs alone.
Objašnjenje (HR)
response.ok se cita izravno, a baceni error nosi status kod, statusText i id pa se kvarovi mogu dijagnosticirati samo iz logova.
Exceptions / Tradeoffs (EN)
If response can genuinely be undefined (e.g. a wrapper that may return null on abort), keep the guard — but then the type, not optional chaining at the call site, should express that.
Iznimke / Tradeoffi (HR)
Ako response stvarno moze biti undefined (npr. wrapper koji vraca null pri abortu), zadrzi provjeru — ali tada to treba izraziti tipom, a ne optional chainingom na pozivnom mjestu.