Loading Depth Study
Preparing your workspace
Centralized error handling prevents duplicated error-response logic and keeps API behavior consistent.
Express applications can use a final error-handling middleware to convert errors into HTTP responses. Route handlers and services can pass failures to the error handler with next(error). A centralized handler can map known errors to appropriate status codes while hiding sensitive implementation details. The API should provide consistent error shapes so frontend clients know how to display failures.
A course API can return 404 for a missing course, 400 for invalid data, 401 for missing authentication, and 500 for unexpected server failures.
function errorHandler(error, req, res, next) {
console.error(error);
res.status(error.statusCode ?? 500).json({
error: error.message ?? 'Internal server error'
});
}
app.use(errorHandler);Unhandled application errors are converted into a consistent JSON error response.