This is the code in question:
import express from 'express';
// Non existing routes
app.use((req: Request, res: Response, next: NextFunction) => {
return next(new Error('Test error));
});
// Error handling
// Arbitrary example
app.use((error: any, req: Request, res: Response) => {
res
.status(500)
.json({ 'Server error' });
});
The problem is, for example when an error is passed in the next()
function in the missing routes middleware it doesn't get to the error handling middleware and as result html instead of json is returned to the client.
I was able to resolve this problem by adding next
argument in the error handling middleware:
// Error handling
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
res
.status(500)
.json({ 'Server error' });
});
It is interesting what might be the cause for this behaviour, because this middleware function was working without this argument before adding typescript.