'In express typescript app, error passed with next() does not get to error handling middleware

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.



Solution 1:[1]

the error handler function is a kind special of middleware that express uses to catch any errors, this middleware must have exactly four parameters as follow:

  1. error is instance of any error or you can specify the kind of error that you want to catch,
  2. The request object
  3. The response object
  4. The next function, this is necessary because you can declare as many error handler as you want and you can continue the flow calling next.

All the for parameters as required.

// Error handling
// Arbitrary example
app.use((error: any, req: Request, res: Response, next: NextFunction) => 
{
  res
    .status(500)
    .json({ 'Server error' });
});

Also the error handler middleware must be declared at the end after the routes handlers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andres Rene Gutierrez T