0

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?

3
  • you are trying to use a global error handler in combination with routers which in my experience does not work. You have to declare an error handler for each router. Commented Apr 28, 2022 at 7:20
  • @TobiasS. can you please provide an example on how that is made? Because this logic works with Node Js with JavaScript and I've used it many times before. But in typescript it does not seem to work Commented Apr 28, 2022 at 7:20
  • routes.use((err, req, res, next) => and then supply the same error handler function Commented Apr 28, 2022 at 7:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer! The 404 error handling worked, but for the other one I get this error on all 4 params: Parameter 'error' implicitly has an 'any' type, but a better type may be inferred from. What can be used as type and can you please provide a code example of 500 error
@nour - I'm not a TypeScript guy, but the error parameter is nearly always an instance of the Error class (or a subclass). You already have code for sending a 500 error in your question - I'm not sure what else you want. It's up to you what you send for a 500 error. That really depends upon your API design and what you want your clients to get when there's an internal server error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.