【发布时间】:2020-10-27 02:08:00
【问题描述】:
我有这段代码调用一个函数并有一个带有错误和数据参数的回调:
app.get('/lights', (req,res) => {
hue.getLights(function(err, data){
if(err) res.status(401).send("An error occured: ", err.message);
res.send(data);
});
})
它调用的函数是:
let getLights = function(callback){
fetch(`http://${gateway}/api/${username}/lights`, {
method: 'GET'
}).then((res) => {
if(res.ok){
return res.json();
}else{
throw new Error(res.message);
}
}).then((json) => {
lightsArray = []
for (var i in json){
lightsArray.push(`ID: ${i} Name: ${json[i]['name']}`);
}
return callback(lightsArray);
});
}
当我发生错误时,未捕获错误,也未显示任何错误,应用程序崩溃并显示以下消息:UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
现在我知道我错过了很多,这是我第一次使用回调,更不用说处理错误了。
有人可以帮助我使错误回调起作用,还可以向我展示我正在做的一些缺陷,因为我知道这不会捕获所有可能发生的错误,只会捕获使用 fetch 函数引起的错误。
谢谢!
这是我的另一个功能(类似但也使用了一个 catch,我认为我也做错了):
let getLightDetails = function (ID, callback) {
fetch(`http://${gateway}/api/${username}/lights/${ID}`, {
method: 'GET'
}).then((res) => {
if(res.ok){
return res.json();
}else{
throw new Error(res.message);
}
}).then((json) => {
return callback(json);
})
.catch((err) => {
console.log(err);
return callback(err.message);
});
}
【问题讨论】:
-
将错误处理(通过
.catch)添加到.thens 链的末尾。你不需要返回承诺,因为无论如何你都是通过回调来处理的。但是,在这种情况下,您应该考虑完全或始终使用节点样式callback(err, data)回调来转换回调样式代码。 -
你可以使用.catch来处理错误
-
@CRice 你能看看我编辑过的帖子吗?我添加了另一个类似的功能,但我认为我使用 .catch 错误
标签: javascript node.js error-handling promise callback