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?
CodePudding user response:
The Express 404 error handler is of this form:
app.use((req, res, next) => {
res.status(404).send({msg: "404 route not found"});
});
You just make sure this is AFTER any routes you have defined.
Your four parameter error handler:
app.use((error, req, res, next) => {
// put error handling code here
});
Is for a different type of error where a specific Error object has already been created by the error such as a synchronous exception occurring in a route or someone calling next(err)
. This four argument error handler does not come into play just because no route matched an incoming request.