Handle Runtime Errors in Express
Express·3 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:
-
Catch the error.
-
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)