↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

The 80/20 Guide to Express Error Handling

Express error-handling middleware centralizes HTTP error response logic so you do not have to repeat try/catch and status-code handling in every route. The post shows that error handlers are middleware with four arguments, must come last in the chain, and only receive errors passed through next().

Reading notes
#

  • A small number of endpoints can use local try/catch, but that approach becomes hard to maintain across many routes.
  • Changing a response code or adding dev-only stack traces is easier when error handling is centralized.
  • Error-handling middleware is identified by four arguments and runs only when an error is present.
  • Errors thrown asynchronously will crash the server unless they are passed to next().
  • Route handlers can accept next() and use it to forward async errors.
  • Error handlers must be defined after the other middleware, or Express will not reach them.
  • async functions return promises, so a helper like wrapAsync() can call .catch(next) and send async failures to the error chain.
  • Separate handlers can map different error types to different HTTP responses, such as assertion errors to 400 and database errors to 503.
  • The overall goal is to keep error handling out of business logic and let middleware decide how to answer the request.