I need all the errors returning from api to be is a specific json format. So when I add the middleware error handling logic to my Node JS typescript app to catch route errors, it does not work.
My app.ts file:
import express, { Application, Request, Response, NextFunction } from 'express';
import routes from './src/start/routes';
import cors from 'cors';
require('dotenv').config();
const app: Application = express();
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use('/', require('./src/routes/api.route'));
app.use('/api', routes);
//Error Handler
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
return res.status(500).json({
status: 500,
success: 0,
message: 'Error',
error: ['Server error.'],
data: {}
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`http://localhost:${PORT}`));
So if I enter a wrong route for example, I get the error 'Cannot GET /WrongRoute' in a single string format and not in the json format that I need. What to do?
routes.use((err, req, res, next) =>and then supply the same error handler function