簡體   English   中英

藍鳥未處理的錯誤與發出NodeJS

[英]Bluebird unhandled Error with emit NodeJS

我使用Bluebird v2.8.2 Promise,但是我收到未處理的錯誤,並且未處理catch中的代碼。

編輯回復:

var Promise = require('bluebird')
    util = require('util')
    EventEmitter = require('events').EventEmitter;

var Module = function() {
    EventEmitter.call(this);
};

util.inherits(Module, EventEmitter);

var getData = function() {
    return Promise.reject(new Error('test'));
};


Module.prototype.getCustomer = function() {
    var self = this;        

    setTimeout(function() {
        getData().then(function() {})
            .catch(function(error) {
                self.emit('error', error); // This causes problem!!
            });
    }, 1000);
}

已解決: Esailija的最新評論

可以很好地處理它,但是在catch處理程序中的代碼很可能出現了錯誤並引發了錯誤。 建議您更仔細地閱讀未處理的錯誤,以查看錯誤原因。

等效的同步代碼的行為方式相同:

   try {
        throw new Error("test");
   } catch (e) {
        causesUnhandledReferenceError;
   }

如果您想捕獲該錯誤(您肯定不是,只是為了鍛煉),則需要另一個try catch:

try {
    throw new Error("test");
} catch (e) {
    try {
        doesntCauseUnhandledReferenceError;
    } catch (e) {
        // logs reference error
        console.log(e)
    }
}

與承諾類似:

getData().then(function() {

}).catch(function(e) {
    doesntCauseUnhandledReferenceError;
}).catch(function(e) {
      // logs reference error
      console.log(e)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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