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

Time:01-27

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.

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related