Rules Hub

Coding Rules Library

← Back to all rules
backend ruleStack: node
validationerror-handlingapi-integrationdefensive-programmingclean-code

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.

PR: Feat/FCK-1669 - Adding Job Landing Page #3656Created: Dec 8, 2025

Bad example

Old codets
1public 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

New codets
1public 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.