0
0
Expressframework~15 mins

Error-handling middleware signature in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Error-handling middleware signature
📖 Scenario: You are building a simple Express server that needs to handle errors gracefully. To do this, you will create an error-handling middleware function with the correct signature so Express can recognize it and use it properly.
🎯 Goal: Create an error-handling middleware function in Express with the correct four-parameter signature: err, req, res, and next. This middleware should send a 500 status code and a JSON response with an error message.
📋 What You'll Learn
Create a basic Express app instance called app
Define an error-handling middleware function with parameters err, req, res, and next
Inside the middleware, send a 500 status code and a JSON response with { error: 'Internal Server Error' }
Use app.use to register the error-handling middleware
💡 Why This Matters
🌍 Real World
Error-handling middleware is essential in Express apps to catch and respond to errors gracefully, improving user experience and debugging.
💼 Career
Knowing how to write and register error-handling middleware is a key skill for backend developers working with Express.js.
Progress0 / 4 steps
1
Create Express app instance
Write a line to import Express and create an app instance called app using express().
Express
Need a hint?

Use import express from 'express' and then const app = express().

2
Define error-handling middleware function
Write a function called errorHandler with parameters err, req, res, and next. Inside, send a 500 status code and a JSON response with { error: 'Internal Server Error' } using res.status(500).json().
Express
Need a hint?

The error handler must have four parameters: err, req, res, and next. Use res.status(500).json({ error: 'Internal Server Error' }) inside.

3
Register error-handling middleware
Use app.use to register the errorHandler middleware function.
Express
Need a hint?

Use app.use(errorHandler) to add the error handler to the app.

4
Add a test route that triggers an error
Add a GET route at /error that calls next(new Error('Test error')) to trigger the error handler.
Express
Need a hint?

Use app.get('/error', (req, res, next) => { next(new Error('Test error')) }) to create the route.