Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Return typed result unions from validators instead of booleans or throws
Return structured validation results when callers need failure details; predicates and throwing validators remain valid for their own contracts.
Bad example
| 1 | // Bare boolean: caller has to re-derive the reason, and nothing ties the message to the failure case |
| 2 | export const validateMaxAge = (maxAgeDays: number, maxLimit: number): boolean => { |
| 3 | return maxAgeDays >= 1 && maxAgeDays <= maxLimit; |
| 4 | }; |
| 5 |
|
| 6 | // Route: error message duplicated / disconnected from the validator |
| 7 | if (!validateMaxAge(maxAgeDays, 365)) { |
| 8 | return res.status(400).json({ error: 'maxAgeDays must be between 1 and 365 days.' }); |
| 9 | } |
| 10 |
|
| 11 | // Or: throwing couples the validator to control flow and transport |
| 12 | export const validateMaxAgeOrThrow = (maxAgeDays: number, maxLimit: number): void => { |
| 13 | if (maxAgeDays < 1 || maxAgeDays > maxLimit) throw new Error('bad maxAge'); |
| 14 | }; |
Explanation (EN)
A bare boolean loses failure details when callers need a specific reason.
Objašnjenje (HR)
Sam boolean gubi pojedinosti neuspjeha kada je pozivatelju potreban konkretan razlog.
Good example
| 1 | type Validation = { valid: true } | { valid: false; error: string }; |
| 2 | function validateMaxAge(days: number, limit: number): Validation { |
| 3 | if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError("Invalid limit"); |
| 4 | if (!Number.isSafeInteger(days) || days < 1 || days > limit) { |
| 5 | return { valid: false, error: `Age must be an integer from 1 to ${limit}` }; |
| 6 | } |
| 7 | return { valid: true }; |
| 8 | } |
Explanation (EN)
The result distinguishes invalid user input, including NaN and fractions; an invalid programmer-supplied limit remains an explicit precondition failure.
Objašnjenje (HR)
Rezultat razlikuje neispravan korisnički unos, uključujući NaN i razlomke. Neispravno programski zadano ograničenje ostaje izričito kršenje preduvjeta.
Notes (EN)
Use a discriminated result when callers need both validity and structured failure details; keep validation independent from HTTP response decisions.
Bilješke (HR)
Koristi diskriminirani rezultat kada pozivateljima trebaju valjanost i strukturirane pojedinosti pogreške. Validaciju odvoji od odluka o HTTP odgovoru.
Exceptions / Tradeoffs (EN)
Boolean predicates are valid when only a yes/no answer is needed. Throwing validators are also valid in an established exception-based contract. Rich schemas can return multiple issues and localization keys.
Iznimke / Tradeoffi (HR)
Boolean predikat valjan je kada je potreban samo odgovor da ili ne. Validator koji baca pogrešku valjan je u ugovoru temeljenom na iznimkama. Bogatije sheme mogu vratiti više problema i ključeve za prijevod.