Premium lesson

Handling Errors in Express.js

Express.js·6 min read·Jan 1, 2025

In Express, runtime errors are handled by a special component called an error-handling middleware.

Its role is to catch these errors to prevent the application from crashing and to respond to clients with an error message indicating that something went wrong when trying to process the request.

The default error-handling middleware

By default, when an error is raised outside of a try...catch block, the built-in error-handling middleware will:

  1. Catch the error.

  2. Log it in the application's console:

    RangeError: Division by zero    at /Users/razvan/learnbackend/server/index.js:8:15    at Layer.handle [as handle_request] (/Users/razvan/learnbackend/server/node_modules/express/lib/router/layer.js:95:5)    at next (/Users/razvan/learnbackend/server/node_modules/express/lib/router/route.js:144:13)    at Route.dispatch (/Users/razvan/learnbackend/server/node_modules/express/lib/router/route.js:114:3)    at Layer.handle [as handle_request] (/Users/razvan/learnbackend/server/node_modules/express/lib/router/layer.js:95:5)    at /Users/razvan/learnbackend/server/node_modules/express/lib/router/index.js:284:15    at Function.process_params (/Users/razvan/learnbackend/server/node_modules/express/lib/router/index.js:346:12)    at next (/Users/razvan/learnbackend/server/node_modules/express/lib/router/index.js:280:10)
icon light bulb key

Unlock the Build RESTful APIs in Node.js module

Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.

You get immediate access to:

  • 37 focused lessons across MySQL, Sequelize, backend, and Express
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module