Search code examples
typescriptexpresserror-handlingmiddleware

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

  • 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.