Error-handling middleware in Node.js
📖 Scenario: You are building a simple Node.js server using Express. You want to handle errors gracefully so users get friendly messages instead of server crashes.
🎯 Goal: Create an Express app with a route that triggers an error, then add error-handling middleware to catch and respond with a JSON error message.
📋 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 error-handling middleware with four parameters:
err, req, res, nextIn the middleware, respond with status code
500 and JSON { error: err.message }💡 Why This Matters
🌍 Real World
Error-handling middleware is essential in real web servers to prevent crashes and provide users with clear error messages.
💼 Career
Understanding error middleware is a key skill for backend developers working with Node.js and Express.
Progress0 / 4 steps