2017-09-11 40 views
1

設P是一個承諾,我們可以做如何處理來自多個錯誤,然後抓住javascript promise?

p 
.then(f1) 
.then(f2) 
.then(f3) 
.catch(f4) 
現在抓

,錯誤可以從任何F1,F2的拋出,F3或甚至p拒絕

現在應該是什麼處理的正確方法錯誤在f4中(或在catch中),因爲上面引發的錯誤可能是不同的類型,如果在f4 中可以避免多個錯誤,

回答

0

只要定義一個額外的catch回調:

p 
.then(f1) 
.then(f2) 
.then(f3) 
.catch(err => { 
    if (/* is expected error */) { 
    console.log(err); 
    return; 
    } 
    throw new Error('Unexpected error'); 
}) 
.catch(err => ...) 
0

你可以定義你自己的自定義錯誤。例如:

function CustomError(errorText){ 
    this.error = errorText; 
} 

修改您的功能。

function p(){ 
    return new Promise(function(resolve, reject){ 
      //Your functionality here 
     }) 
      .catch(function(error){ 
      Promise.reject(new CustomError('f1'))); 
     }) 
} 

等等:添加catch塊每一個承諾從函數返回F2,F3,F4

而且你的catch塊將是:

.catch((err) => { 
    if(err instanceof CustomError){ 
     HandleCustomError(err); 
    } else { 
     //Some another error is happen 
    } 
}) 

你自定義的錯誤處理程序將是這樣的:

function HandleCustomError(customError){ 
    switch(customError.error){ 
     case 'f1': 
      //handle f1 
      break; 
     case 'f2': 
      //handle f2 
      break; 
     ... 
    } 
}