An Error Response
Part of the Express Basics section of Coddy's Node.js journey. Lesson 17 of 23.
A route can fail because something on the server went wrong. Throwing an Error hands that failure to Express. An error handler is middleware with four parameters, including err first. Express sends thrown errors to this kind of middleware.
app.use((err, req, res, next) => {
res.status(500).json({error: 'Try later'});
});Place the handler after the routes. The client should receive a short message, while the server can log the details. Keep all four parameters even if next is unused: Express uses the function shape to recognize error handlers.
Before adding a handler, GET /broken returns Express’s own HTML error page. Calling next(err) also forwards an error to the error handler; calling next() continues normally.
Challenge
EasyRun starts only practice-errors/server.js. Your Recipe Box files are untouched and you continue them in the next lesson.
Run and send GET /broken to see the default error page. Add an error handler after the routes. Log err.message with console.error, then send status 500 and {"error":"Try later"}. The response must not expose Database offline, but the Console must show it.
The throwing routes live in the locked practice-errors/routes.js. Keep its mount; write the handler in server.js.
Try it yourself
import routes from './routes.js';
import express from 'express';
const app = express();
app.use(routes);
// Add the error handler here.
app.listen(3000);
All lessons in Express Basics
3Middleware
Your First MiddlewarePractice on your own: Express playground