Rules Hub
Coding Rules Library
Validate inputs and handle upstream 404s in providers
Always validate required arguments before using them in external requests and explicitly handle upstream 404 responses to distinguish missing data from errors.
Bad example
| 1 | public async getProduct(id: string): Promise<Product> { |
| 2 | // Dangerous: No validation. If id is empty, the URL might be malformed or fetch a list instead of an item. |
| 3 | const res = await fetch(`${this.apiUrl}/products/${id}`); |
| 4 | |
| 5 | // Dangerous: No status check. If the API returns 404 (Not Found), |
| 6 | // res.json() might fail (if body is HTML) or return an error object instead of the expected Product. |
| 7 | return res.json(); |
| 8 | } |
Explanation (EN)
The code constructs a URL and fetches data without validating the input `id` or checking the response status. If `id` is missing or the upstream service returns a 404, the application may crash during JSON parsing or return invalid data.
Objašnjenje (HR)
Kod konstruira URL i dohvaća podatke bez validacije ulaznog parametra `id` ili provjere statusa odgovora. Ako `id` nedostaje ili vanjski servis vrati 404, aplikacija se može srušiti tijekom parsiranja JSON-a ili vratiti neispravne podatke.
Good example
| 1 | public async getProduct(id: string): Promise<Product | null> { |
| 2 | // 1. Validate inputs immediately (Guard Clause) |
| 3 | if (!id) { |
| 4 | console.warn('getProduct called without ID'); |
| 5 | return null; |
| 6 | } |
| 7 |
|
| 8 | const res = await fetch(`${this.apiUrl}/products/${id}`); |
| 9 |
|
| 10 | // 2. Handle expected "Not Found" explicitly |
| 11 | if (res.status === 404) { |
| 12 | return null; |
| 13 | } |
| 14 |
|
| 15 | // 3. Handle generic errors |
| 16 | if (!res.ok) { |
| 17 | throw new Error(`Upstream error: ${res.status} ${res.statusText}`); |
| 18 | } |
| 19 |
|
| 20 | return res.json(); |
| 21 | } |
Explanation (EN)
Input validation ensures no invalid requests are sent. Checking specifically for `res.status === 404` allows the method to return `null` (meaning 'not found') gracefully, distinguishing it from actual system failures.
Objašnjenje (HR)
Validacija ulaznih podataka osigurava da se ne šalju neispravni zahtjevi. Eksplicitna provjera `res.status === 404` omogućuje metodi da graciozno vrati `null` (što znači 'nije pronađeno'), jasno razlikujući taj slučaj od sistemskih grešaka.