Rules Hub
Coding Rules Library
Terminate invalid requests with explicit HTTP errors
Return a 4xx response immediately when validation fails instead of calling next(), which passes control to subsequent handlers.
Bad example
| 1 | app.get('/api/resource/:id', (req, res, next) => { |
| 2 | const { id } = req.params; |
| 3 | |
| 4 | if (!isValidId(id)) { |
| 5 | // Bad: Calling next() passes control to the next route handler, |
| 6 | // often causing a 404 or unexpected behavior instead of a clear error. |
| 7 | return next(); |
| 8 | } |
| 9 |
|
| 10 | return res.json({ id }); |
| 11 | }); |
Explanation (EN)
Calling `next()` when input validation fails causes the request to fall through to subsequent routes or the 404 handler. This obscures the actual error (bad input) and confuses the client.
Objašnjenje (HR)
Pozivanje `next()` kada validacija ne uspije prosljeđuje zahtjev sljedećim rutama ili 404 handleru. To skriva pravu grešku (neispravan unos) i zbunjuje klijenta.
Good example
| 1 | app.get('/api/resource/:id', (req, res) => { |
| 2 | const { id } = req.params; |
| 3 |
|
| 4 | if (!isValidId(id)) { |
| 5 | // Good: Explicitly terminate with a 400 Bad Request. |
| 6 | return res.status(400).send('Invalid resource ID'); |
| 7 | } |
| 8 |
|
| 9 | return res.json({ id }); |
| 10 | }); |
Explanation (EN)
If the request is malformed or missing required data, the server should explicitly respond with a 400 Bad Request status. This provides immediate, clear feedback to the API consumer.
Objašnjenje (HR)
Ako je zahtjev neispravan ili nedostaju podaci, server treba eksplicitno odgovoriti statusom 400 Bad Request. To pruža trenutnu i jasnu povratnu informaciju korisniku API-ja.