Error-handling middleware
📖 Scenario: You are building a simple Express server that handles user requests. Sometimes errors happen, like when a user asks for a page that does not exist. To keep your server friendly and clear, you want to add a special error-handling middleware that catches errors and sends a nice message back to the user.
🎯 Goal: Create an Express app with a route that triggers an error, then add an error-handling middleware that catches the error and sends a JSON response with the error message and a 500 status code.
📋 What You'll Learn
Create an Express app instance called
appAdd a route
/cause-error that throws an error with message 'Something went wrong!'Create an error-handling middleware function with four parameters:
err, req, res, nextIn the error handler, send a JSON response with
status 500 and message from the errorUse
app.use to add the error-handling middleware after the route💡 Why This Matters
🌍 Real World
Error-handling middleware helps keep web servers stable and user-friendly by catching unexpected problems and sending clear messages.
💼 Career
Understanding error-handling middleware is essential for backend developers working with Express to build reliable and maintainable web applications.
Progress0 / 4 steps