如何在Node.js的回调中处理错误

发布时间:2020-07-06 21:23

我有这段代码可以调用一个函数,并具有一个带有错误和数据参数的回调:

RadioButton

它调用的函数是:

CornerRadius

当我发生错误时,未捕获到该错误,也未显示任何错误,该应用程序崩溃并显示以下消息:app.get('/lights', (req,res) => { hue.getLights(function(err, data){ if(err) res.status(401).send("An error occured: ", err.message); res.send(data); }); })

现在我知道我很想念,这是我第一次使用回调,更不用说处理错误了。

有人可以帮助我使错误回调正常工作吗,还可以向我展示我所做的一些缺陷,因为我知道这不会捕获可能发生的所有错误,而只能捕获使用fetch函数引起的错误。 / p>

谢谢!

这是我的另一个功能(类似,但是也使用了catch,我想我也做错了):

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);
    });
}
回答1

混合回调和Promise会使您的代码有些混乱。我会遵守诺言:

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 };