Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node JS with typescript failing to catch express errors using middleware

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading