Express error Handler does not work

Asked

Viewed 21 times

0

I have an express server where the index is written as follows:

import 'express-async-errors';
import express, { NextFunction, Request, Response } from 'express';
import { CelebrateError, isCelebrateError } from 'celebrate';
import cors from 'cors';
import { config } from 'dotenv';

import { routes } from './routes';
import { RequestError } from './models/RequestError';
import { StatusCodes } from './models/StatusCodes';

config();

const port = process.env.PORT || 3333;

const app = express();

app.use(express.json());
app.use(cors());
app.use(routes);
app.use((err: RequestError | CelebrateError, request: Request, response: Response, next: NextFunction) => {
  if (isCelebrateError(err)) {
    return response
      .status(StatusCodes.BAD_REQUEST)
      .json(err.details.get('body')?.details[0]);
  }

  if (isNaN(err.code)) console.log(err);
  
  return response
    .status(err.code ?? StatusCodes.INTERNAL_SERVER_ERROR)
    .json({ message: err.message });
});

app.listen(port, () => {
  console.log(`Server running on port: ${port}`);
});

However the standard Node Handler error is not capturing the error (Even if you import express-async-errors into asynchronous routes), I have another application in the same way that Handler error captures the errors without problem, I can’t understand what might be going wrong.

  • I won’t say because I won’t be able to test it now, but I vaguely remember that in a project I needed to create an error class extending the Error, something like: class MeuErro extends Error. Every time I made a mistake I threw one new MeuErro() and the error arrived in Handler without problems. Maybe this helps you

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.