'Node js with typescript; How to catch express errors
So if I am using node js with javascript, I used to catch errors by adding the following code in my app.js startup file:
app.use((req, res, next) => { next(createError.NotFound()); });
app.use((err, req, res, next) => {
res.status(err.status || 500).json({
status: err.status || 500,
success: 0,
message: 'Error',
error: [err.message],
data: {}
});
});
the "err" will be automatically caught and it will return for example 404 if I am using a route that does not exist or 500 if the database connection is not established correctly and so on.
But in typescript, how can I do the same logic?
My app.ts file is as follows
import express, { Application, Request, Response, NextFunction } from 'express';
import routes from './start/routes';
const app: Application = express();
app.use('/', require('./routes/api.route'));
app.use(express.json());
app.use('/api', routes);
app.use((err, req: Request, res: Response, next: NextFunction ) => {
res.status(err.status || 500).json({
status: err.status || 500,
success: 0,
message: 'Error',
error: [err.message],
data: {}
});
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`🚀 @ http://localhost:${PORT}`));
this is not compiling. It says that err.status and err.message are not found. What to do?
Solution 1:[1]
You are missing the type for the err
parameter, which should be any
according to the ErrorRequestHandler
type.
This will make your code compile, and the handler will run automatically when an error occurs.
To make a default response to 404 though. You will need to add another handler since it's not an error.
app.use((req: Request, res: Response, next: NextFunction ) => {
// Handle not found
})
NOTE This handler should be last since it accepts every request.
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 | Amit Keinan |