如何在 Nodejs 的回调中处理错误
How to handle errors from within a callback in Nodejs
我有这段代码调用一个函数并有一个带有错误和数据参数的回调:
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);
});
}
混合使用回调和承诺会使您的代码有点混乱。我会信守承诺:
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 };
我有这段代码调用一个函数并有一个带有错误和数据参数的回调:
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);
});
}
混合使用回调和承诺会使您的代码有点混乱。我会信守承诺:
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 };