简体   繁体   中英

Overriding express general error handling

I am trying to override express general error handling with a json object but it's not working.

The way I test it is by making a http get call which the route for doesn't exist.

I added the error handling middleware and still when I made a bad request this is what gets returned.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/image/initialize</pre>
</body>
</html>

here is the 'main' function:

async function main() {

  // the startup initialization code, handle any initialization
  // code in the startup folder, and call thh function in index.js
  const {
    settings,
    projectCol
  } = await initialize();

  port = normalizePort(process.env.PORT || DEFAULT_PORT);
  var app = express();

  // view engine setup
  app.use(logger('dev'));
  app.use(express.urlencoded({ extended: true }));
  app.use(express.json());
  app.use(cookieParser());

  // allow so it be used on the same PC
  app.use( function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

  // setup routes
  setupRoutes(app, { projectCol, settings });

  app.set('port', port);

  // error handling
  app.use( function (err, req, res, next) {

    if (res.headersSent) {
      return next(err)
    }

    return res.status(500).json({
        error: err.message
    });
  })

  app.listen(port);
  app.on('error', onError);
  app.on('listening', onListening);
}

took me a long time to figure out so here is the answer of people who might stumple on this. If the path is not found, you have to add a catch all route and forward that to the error handler.

  app.get('*', function(req, res, next) {
    let err = new Error(`${req.originalUrl} doesn't exist`); // Tells us which IP tried to reach a particular URL
    err.statusCode = 404;
    err.shouldRedirect = true; //New property on err so that our middleware will redirect
    next(err);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM