Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
backend ruleP1universalStack: Node.js
ormnull-safetyerror-handling
Handle the null result of a single-record lookup
A `findOne`/`findByPk`/`find` that matches nothing returns null/undefined, not an error. Guard the not-found case (throw a named error or return early) before dereferencing, or the next property access throws a generic runtime error.
PR: profico-org-corpus batch2 (all stacks/products)Created: Jul 26, 2026
Bad example
Old codets
| 1 | const user = await User.findOne({ where: { email } }); |
| 2 | return user.role; // throws if no user matched |
Explanation (EN)
When no row matches, `user` is null and `.role` throws an opaque TypeError.
Objašnjenje (HR)
Good example
New codets
| 1 | const user = await User.findOne({ where: { email } }); |
| 2 | if (!user) throw new NotFoundError('user'); |
| 3 | return user.role; |
Explanation (EN)
The not-found case is handled explicitly with a meaningful error.
Objašnjenje (HR)