2016-03-18 15 views
0

我正在尋找更容易/更簡單的方式來創建錯誤功能,我只是尋找一種簡單的方法來退出承諾鏈。您可以在下面看到一個錯誤對象NoUserFound和承諾鏈。我期待的結果是當model.readUserAddresses返回false我拋出一個特定的錯誤跳過承諾鏈。是否有更簡單更直接的(單行)方法來創建NoUserFound自定義錯誤只是爲了這個目的?使用自定義錯誤退出/中斷承諾

function NoUserFound(value) { 
    Error.captureStackTrace(this); 
    this.value = value; 
    this.name = "NoUserFound"; 
} 
NoUserFound.prototype = Object.create(Error.prototype); 

model.readUserAddresses(email) 
    .then(ifFalseThrow(NoUserFound)) 
    .then(prepDbCustomer) 
    .then(shopify.customerCreate) 
    .catch(NoUserFound,() => false) 

理想情況下,我可以做這樣的事情。

model.readUserAddresses(email) 
    .then(ifFalseThrow('NoUserFound')) 
    .then(prepDbCustomer) 
    .then(shopify.customerCreate) 
    .catch('NoUserFound',() => false) 

而不一定有一個無用的一次性錯誤類。

+1

想一想,如果鏈條中的第一個承諾引發了實際的錯誤,這可能是最好的。 – ThomasReggi

+0

即時通訊實現Promise in Native,但在[bluebird](https://github.com/petkaantonov/bluebird)中可以很好地實現,您可以在此處爲承諾 – kiro112

+0

函數ifFalseThrow(e ){return function(v){if(!v)throw new Error(e)}}' – dandavis

回答

2

如果你不想建立自己的錯誤類,您還可以使用Bluebird's builtin error types之一,即一個OperationalError

model.readUserAddresses(email) 
    .then(ifFalseThrow(Promise.OperationalError)) 
    .then(prepDbCustomer) 
    .then(shopify.customerCreate) 
    .error(() => false) 

如果不能滿足您的需求(例如,由於OperationalError已經被用於別的東西),你實際上不必把它定製成一個自定義的錯誤類型(子類)。 catch也需要簡單的斷言功能,讓你可以像

model.readUserAddresses(email) 
    .then(ifFalseThrow(Error, "noUserFound")) 
    .then(prepDbCustomer) 
    .then(shopify.customerCreate) 
    .catch(e => e.message == "noUserFound",() => false) 

最後但並非最不重要的,拋出異常是不是如果你想要的是跳過您鏈的一部分最好的主意。相反分支明確:

model.readUserAddresses(email) 
    .then(userAddresses => 
    userAddresses 
     ? prepDbCustomer(userAddresses) 
     .then(shopify.customerCreate) 
     : false 
) 

(縮短該回調由您自行決定,如.then(u => u && prepDbCustomer(u).then(shopify.customerCreate))

1

我嘗試這樣做。

model.readUserAddresses(email) 
.then((status) => { 
    if(!status) { 
     var error = new Error('No user Found'); 
     error.customMessage = 'customMessage'; 
     error.name = 'customeName'; 
     throw error; 
    } 
}) 
.then(prepDbCustomer) 
.then(shopify.customerCreate) 
.catch((err) { 
    console.log(err); 
}) 

我建議創建一個customeError對象來處理錯誤。

+0

OP alread *是*創建自定義錯誤(類'NoUserFound')? – Bergi

+0

好,因爲OP在創建自定義錯誤'NoUserFound'類時猶豫不決,所以我認爲這可能是一種處理錯誤的可能方式。說實話,我會建議他堅持customeError類。 – Putty