Chapter 2 of 7 · 4 practices · 3 min · 4-question quiz
Validation and error handling
Check every input at the edge, handle failures in one place, and keep internal details out of responses.
Start: Validate the body, params, query and headers of every request4 practices in this chapter
- 1Validate the body, params, query and headers of every requestEverything in a request is untrusted: body, path params, query string, headers and cookies. Validate each one against a schema before your code uses it.
- 2Handle errors in one central error handlerScattering
try/catchblocks with their own response code in every route leads to inconsistent status codes and leaked messages. Handle errors in one place instead. - 3Never send stack traces or database errors to clientsA stack trace or raw database error in a response tells an attacker your framework, file paths, table names and sometimes your query structure.
- 4Log and exit on uncaught exceptions instead of carrying onAn uncaught exception or unhandled rejection means your process is in an unknown state. Catching it and carrying on can leave half-finished writes, leaked connections or corrupted memory.
Check yourself on this chapter
4 questions, right here once you are signed in. Your progress is saved as you read.