一尘不染

Express JS错误处理

node.js

我正在尝试通过express运行错误处理,但没有看到“错误!”的响应。就像我希望在控制台上看到“某些异常”一样,然后该进程被终止。这是应该如何设置错误处理的,如果可以的话,还有另一种捕获错误的方法吗?

var express = require('express');
var app = express();

app.use(function(err, req, res, next) {
    console.log("error!!!");
    res.send("error!!!");
});

app.get('/', function(request, response) {
    throw "some exception";
    response.send('Hello World!');
});

app.listen(5000, function() {
  console.log("Listening on 5000");
});

阅读 201

收藏
2020-07-07

共1个答案

一尘不染

有关错误处理的示例应用程序/指南可在https://expressjs.com/en/guide/error-
handling.html上找到,
但是应该可以修复您的代码:

// Require Dependencies
var express = require('express');
var app = express();

// Middleware
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the next middleware (your error reporter)
app.use(function(err, req, res, next) {
    if(!err) return next(); // you also need this line
    console.log("error!!!");
    res.send("error!!!");
});

// Routes
app.get('/', function(request, response) {
    throw "some exception";
    response.send('Hello World!');
});

// Listen
app.listen(5000, function() {
  console.log("Listening on 5000");
});
2020-07-07