Let's take a closer look at this code snippet:
import express from 'express';
// Custom error handling for non-existing routes
app.use((req: Request, res: Response, next: NextFunction) => {
return next(new Error('Test error));
});
// Global error handling example
app.use((error: any, req: Request, res: Response) => {
res
.status(500)
.json({ 'Server error' });
});
An issue arises when an error is triggered within the missing routes middleware. This prevents the error from being caught by the global error handling middleware, resulting in HTML responses instead of JSON being sent back to the client.