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).
Propagate a lookup's not-found result instead of forwarding it into unconditional dereferencing code
If a lookup can return null/undefined for "not found", check for that at the call site and return early — don't pass the possibly-missing result into a helper that unconditionally spreads or reads properties off it, since that turns a normal "not found" case into an uncaught runtime throw.
Bad example
| 1 | static async getTranscriptWithSegmentsForUser(transcriptId: number, userId: number): Promise<TranscriptWithSegments> { |
| 2 | const transcript = await TranscriptService.getTranscriptForUser(transcriptId, userId); |
| 3 | return TranscriptService.enrichTranscriptWithSegments(transcript); // throws if transcript is undefined |
| 4 | } |
Explanation (EN)
`getTranscriptForUser` returns `undefined` when the transcript doesn't exist or doesn't belong to the user. Passing that straight into `enrichTranscriptWithSegments`, which spreads it (`{ ...transcript }`), throws a runtime error for what is a completely normal "not found" case instead of surfacing it as a clean not-found result.
Objašnjenje (HR)
`getTranscriptForUser` vraca `undefined` kada transkript ne postoji ili ne pripada korisniku. Prosljedivanje toga direktno u `enrichTranscriptWithSegments`, koja to sirenjem (`{ ...transcript }`) koristi, baca runtime gresku za potpuno normalan "nije pronadjeno" slucaj umjesto da ga prikaze kao cist not-found rezultat.
Good example
| 1 | static async getTranscriptWithSegmentsForUser(transcriptId: number, userId: number): Promise<TranscriptWithSegments | undefined> { |
| 2 | const transcript = await TranscriptService.getTranscriptForUser(transcriptId, userId); |
| 3 | if (!transcript) return undefined; |
| 4 | return TranscriptService.enrichTranscriptWithSegments(transcript); |
| 5 | } |
Explanation (EN)
Returning `undefined` explicitly when the transcript isn't found keeps the service's behavior consistent with callers that already check for a falsy result, and avoids throwing for an expected case.
Objašnjenje (HR)
Eksplicitno vracanje `undefined` kada transkript nije pronadjen odrzava ponasanje servisa dosljednim s pozivateljima koji vec provjeravaju falsy rezultat, i izbjegava bacanje greske za ocekivan slucaj.
Notes (EN)
Same pattern applies wherever a "find" style function's result is passed unchecked into a function that assumes a defined object (spread, property access, method calls).
Bilješke (HR)
Isti obrazac vrijedi gdje god se rezultat funkcije tipa "find" prosljedjuje neprovjeren u funkciju koja pretpostavlja definiran objekt (spread, pristup svojstvu, pozivi metoda).