簡體   English   中英

如何從異步代碼中捕獲錯誤

[英]How to catch error from Asynchronous code

以下代碼行能夠捕獲錯誤(因為它是同步的)

 new Promise(function(resolve, reject) {
        throw new Error("Whoops!");
    }).catch(alert);

但是,當我修改我的代碼時,如下所示

 new Promise(function(resolve, reject) {
      setTimeout(() => {
        throw new Error("Whoops!");
      }, 1000);
    }).catch(alert);

它無法捕獲錯誤。 我有一個用例,我想抓住這個錯誤。 我怎樣才能實現它?

點擊鏈接“ https://bytearcher.com/articles/why-asynchronous-exceptions-are-uncatchable/ ”,我就能理解為什么會這樣。 只是想知道是否還有任何解決方案來捕獲這樣的錯誤。

請注意,通過使用setTimeout,我指的是異步調用的使用,它可以給出一些響應,或者在我在fetch語句中提供不正確的URL時會出現錯誤。

fetch('api.github.com/users1')   //'api.github.com/user'is correct url
.then(res => res.json())
.then(data => console.log(data))
.catch(alert);

你需要一個try / catch你問里面的功能setTimeout調用:

new Promise(function(resolve, reject) {
    setTimeout(() => {
        try {
            throw new Error("Whoops!"); // Some operation that may throw
        } catch (e) {
            reject(e);
        }
    }, 1000);
}).catch(alert);

函數setTimeout調用完全獨立於promise執行器函數的執行上下文。

在上面我假設throw new Error("Whoops!")是可能拋出錯誤的操作的替身,而不是實際的throw語句。 但是,如果你真的在throw ,你可以直接調用reject

new Promise(function(resolve, reject) {
    setTimeout(() => {
        reject(new Error("Whoops!"));
    }, 1000);
}).catch(alert);

使用拒絕拋出錯誤,

new Promise(function(resolve, reject) {
  setTimeout(() => {
    reject(new Error("Whoops!"))
  }, 1000);
}).catch(alert);

要處理錯誤,請將try-catch放在setTimeout處理程序中:

 new Promise(function(resolve, reject) {
      setTimeout(() => {
          try{
                  throw new Error("Whoops!");
          }catch(alert){
                  console.log(alert);
          }
       }, 1000);
 });

你也可以用一點實用工具:

function timeout(delay){ 
  return new Promise(resolve => setTimeout(resolve, delay)); 
}

timeout(1000)
  .then(() => {
     throw new Error("Whoops!");
  })
  .catch(alert);

暫無
暫無

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

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