哪个错误将由express错误和uncaughtException错误处理程序处理?
问题描述:
在我使用express nodejs的服务中。我知道明确的错误处理程序,与ERR第一哪个错误将由express错误和uncaughtException错误处理程序处理?
app.use(function(err, req, res, next)
回调函数,我们可以通过
process.on('uncaughtException', function(err) {}
其实处理uncaughtException此外,一些uncaughtException会去表达错误处理程序不uncaughtException处理程序。
请帮忙告诉我哪个错误将由express处理,由uncaughtException处理程序处理?
非常感谢
答
当你扔在一个函数的异常(throw new Error(...)
),这是直接从快速调用,它将被逮住,并转发给您的错误处理程序。发生这种情况是因为代码周围有一个try-catch
块。
app.get("/throw", function(request, response, next) {
throw new Error("Error thrown in scope of this function. Express.js will delegate it to error handler.")
});
当你扔在一个函数的异常不直接由快递(延迟或异步代码)呼吁,有没有可用的catch块捕获这个错误并妥善处理。例如,如果你有一些代码被异步执行:
app.get("/uncaught", function(request, response, next) {
// Simulate async callback using setTimeout.
// (Querying the database for example).
setTimeout(function() {
throw new Error("Error thrown without surrounding try/catch. Express.js cannot catch it.");
}, 250);
});
这个错误不会被快速被获取(并转发到错误处理程序),因为有解决这个代码没有包装try/catch块。在这种情况下,将会触发未捕获的异常处理程序。
在一般情况下,如果遇到从中你无法恢复的错误,使用next(error)
正确地转发这个错误你的错误处理程序中间件:
app.get("/next", function(request, response, next) {
// Simulate async callback using setTimeout.
// (Querying the database for example).
setTimeout(function() {
next(new Error("Error always forwarded to the error handler."));
}, 250);
});
下面是一个玩弄一个完整的例子:
var express = require('express');
var app = express();
app.get("/throw", function(request, response, next) {
throw new Error("Error thrown in scope of this function. Express.js will delegate it to error handler.")
});
app.get("/uncaught", function(request, response, next) {
// Simulate async callback using setTimeout.
// (Querying the database for example).
setTimeout(function() {
throw new Error("Error thrown without surrounding try/catch. Express.js cannot catch it.");
}, 250);
});
app.get("/next", function(request, response, next) {
// Simulate async callback using setTimeout.
// (Querying the database for example).
setTimeout(function() {
next(new Error("Error always forwarded to the error handler."));
}, 250);
});
app.use(function(error, request, response, next) {
console.log("Error handler: ", error);
});
process.on("uncaughtException", function(error) {
console.log("Uncaught exception: ", error);
});
// Starting the web server
app.listen(3000);
您能解释更多关于Express直接调用的内容吗? :d。 我是新手,知道很多东西 非常感谢:d – thelonglqd
我用完整的示例更新了我的答案,希望这有助于! – xaviert
非常感谢您的回答! 另外,app.get或者app.post(类似的东西)在传递给express的路由器api时,它们的错误也会被express表示(它发生在我的项目中:D) – thelonglqd