gpt4 book ai didi

node.js - Express js 错误处理

转载 作者:IT老高 更新时间:2023-10-28 22:07:57 27 4
gpt4 key购买 nike

我正在尝试使用 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");
});

最佳答案

有关错误处理的示例应用程序/指南可在 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");
});

关于node.js - Express js 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15684130/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com