【问题标题】:How to handle/catch error with setTimeout? [duplicate]如何使用 setTimeout 处理/捕获错误? [复制]
【发布时间】:2019-06-08 18:00:23
【问题描述】:

function abc() {
  try {
    setTimeout(() => {
      console.log('inside timeout!!');
      throw new Error('Somehting went wrong!!');
    }, 1000);
  } catch (err) {
    console.log('Gonna catch it here and throw is again', err);
    throw new Error(err);
  }
}
try {
  abc();
} catch (err) {
  console.log('err caught here', err);
}

如何捕捉错误?我应该在哪里用 try/catch 包装我的代码? 即使承诺为什么 catch 块没有捕获错误。

async function abc() {
   setTimeout(() => {
     throw new Error();
   }, 1000);
}

try {
  abc();
} catch (err) {
  console.log('err is ', err);
}

【问题讨论】:

  • 你必须把回调包裹起来,因为setTimeout(() => {throw new Error();}, 1000);是一个成功的调用。错误直到稍后才会出现。
  • 您应该拒绝承诺,以便执行 catch 函数。这个catch函数不同于try catch构造来捕捉异常
  • @Xufox,这意味着无法捕获回调函数之外的任何回调函数的错误?

标签: javascript try-catch


【解决方案1】:

将其包装成Promise:

function abc(simulateError) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (simulateError)
        reject('Something went wrong')
      else
        resolve('foo')
    })
  })
}

// Call it using then/catch to handle result or errors...
abc(true).then(result => {
  console.log(result)
})
.catch(err => {
  console.log(err)
})

// or await on the Promise, which allows using try/catch.
;(async () => {
  try {
    const result = await abc(true)
    console.log(result)
  } catch (err) {
    console.log(err)
  }
})()

【讨论】:

  • 任何其他建议,而不是带有承诺的 .catch 块。
  • 是的,error-first callbacks 但这是一种过时的做法。
  • promise 块的 .catch 和普通的 catch 块有什么区别
  • try/catch 在这里帮不了你,即使它在 async 函数中。处理来自 setTimeout 的错误的唯一方法是传递回调或 Promises。
  • 有了Async和await,只需要等待catch块,不是普通catch块的限制吗?
猜你喜欢
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多