Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Enforce timeouts on network requests
Give finite fetch operations an effective deadline and caller cancellation, covering both response headers and required body consumption.
Bad example
| 1 | const fetchData = async () => { |
| 2 | try { |
| 3 | // BAD: No timeout configured. |
| 4 | // If the API hangs, this promise remains pending indefinitely. |
| 5 | const res = await fetch('https://api.example.com/items'); |
| 6 | const data = await res.json(); |
| 7 | setData(data); |
| 8 | } catch (error) { |
| 9 | console.error(error); |
| 10 | } |
| 11 | }; |
Explanation (EN)
A request with no effective deadline can retain resources indefinitely.
Objašnjenje (HR)
Zahtjev bez djelotvornog roka može neograničeno zadržati resurse.
Good example
| 1 | const fetchData = async () => { |
| 2 | const controller = new AbortController(); |
| 3 | // Set a 5-second timeout |
| 4 | const timeoutId = setTimeout(() => controller.abort(), 5000); |
| 5 |
|
| 6 | try { |
| 7 | const res = await fetch('https://api.example.com/items', { |
| 8 | signal: controller.signal |
| 9 | }); |
| 10 | const data = await res.json(); |
| 11 | setData(data); |
| 12 | } catch (error) { |
| 13 | if (error.name === 'AbortError') { |
| 14 | console.error('Request timed out'); |
| 15 | } else { |
| 16 | console.error('Fetch error:', error); |
| 17 | } |
| 18 | } finally { |
| 19 | // Always clear the timer to prevent memory leaks |
| 20 | clearTimeout(timeoutId); |
| 21 | } |
| 22 | }; |
Explanation (EN)
An AbortController is used to explicitly cancel the request if it exceeds the defined timeout. The logic handles the specific 'AbortError' and ensures the timer is cleared in the 'finally' block.
Objašnjenje (HR)
AbortController se koristi za eksplicitno otkazivanje zahtjeva ako pređe definirani limit. Logika obrađuje specifičnu 'AbortError' grešku i osigurava da se timer očisti u 'finally' bloku.
Notes (EN)
For a finite request, enforce an operation deadline through the existing HTTP client or a cancellation signal and keep it active through required body consumption.
Exceptions / Tradeoffs (EN)
A bare AbortController without a timer does not impose a timeout. Preserve parent signals and distinguish a timeout from user cancellation; streaming or long-lived connections need their own policy.