![](/img/trans.png)
[英]How to catch/handle emitted errors within a series of pipes in nodejs?
[英]How to handle errors from within a callback in Nodejs
我有这段代码调用 function 并有一个带有错误和数据参数的回调:
app.get('/lights', (req,res) => {
hue.getLights(function(err, data){
if(err) res.status(401).send("An error occured: ", err.message);
res.send(data);
});
})
它调用的 function 是:
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().
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 function 引起的错误。
谢谢!
这是我的另一个 function (类似但也使用了一个 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);
});
}
混合使用回调和承诺会使您的代码有点混乱。 我会坚持承诺:
app.get('/lights', (req, res) => {
return hue.getLights()
.then(data => {
res.send(data);
})
.catch(err => {
res.status(401).send("An error occured: ", err.message);
});
})
和hue.js
const fetch = require('node-fetch');
const gateway = "192.168.0.12";
const username = "username-A";
function fetchAPI(url, ...rest) {
return fetch(`http://${gateway}/api/${username}${url}`, ...rest);
}
function getLights() {
return fetchAPI(`/lights`)
.then(res => res.json())
.then(json => json.map((light, i) => `ID: ${i} Name: ${light.name}`));
}
function getLightDetails(id) {
return fetchAPI(`/lights/${id}`)
.then(res => res.json());
}
function getLightState(id) {
return fetchAPI(`/lights/${id}`)
.then(res => res.json())
.then(light => `Name: ${light.name} On: ${light.state.on}`);
}
function setLightState(id, state) {
return fetchAPI(`/lights/${id}/state`, {
method: 'PUT',
body: JSON.stringify({"on": state })
}).then(res => res.json());
}
module.exports = { getLights, getLightDetails, getLightState, setLightState };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.