首页 > 解决方案 > 如何使用 setTimeout 处理/捕获错误?

问题描述

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);
}

标签: javascripttry-catch

解决方案


将其包装成一个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)
  }
})()


推荐阅读