簡體   English   中英

如何在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM