TypeError: res.status is not a function in a error handling middleware

Viewed 2511

I simply want to add a minimal middleware to handle errors within my express typescript project.
I use errors method from celebration to let it handle celebration/joi errors, and want to add another one to handler other errors.
Here is my code:

app.use(errors()); // celebration error handling
app.use((err: any, req: Request, res: Response) => res.status(300).json(err.message));

I order to test it I try to send a GET to an endpoint who doesn't exist, and I keep getting this error: TypeError: res.status is not a function

What should I do to be able to use Request like I want ?

1 Answers

If you want to write error handling middleware, you have to provide a function with four declared parameters, not just three. So in your case:

app.use((err: any, req: Request, res: Response, next: NextFunction) => res.status(300).json(err.message));

Even though you don't use the next function in your code, Express can only tell it's an error handler middleware function if it takes four formal parameters. From the documentation linked above:

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.

Express must be looking at the length property of the function in order to know whether it's an error-handling middleware or not.

Related