Error Handling in Express.js

2020-07-27 02:17发布

问题:

How to handle errors in Express.js?

For example, if user calls non-existing resource?

回答1:

If you want to yield a 404 just add this as your last route:

app.get('*', function(req, res){
  res.send('Not Found', 404);
});

So everything that wasn't handled by any other route will results in a 404.

You can find additional information on sending error responses in the section of the expressJS API Reference that covers the send method of the Response object. It is located here.



回答2:

Omen, if you want to cover all HTTP methods use:

app.all('*', function(req, res) {

   // Do something...

});