代码之家  ›  专栏  ›  技术社区  ›  Costa Michailidis

如何用try catch捕获回调错误?

  •  0
  • Costa Michailidis  · 技术社区  · 6 年前

    我有一个异步函数来获取文件的内容,比如:

    async function getFile (name) {
      return new Promise(function (resolve, reject) {
        fs.readFile(`./dir/${name}.txt`, 'utf8', function (error, file) {
          if (error) reject(error)
          else resolve(file)
        })
      })
    }
    

    我把这个函数调用到控制台日志中

    getFile('name').then( console.log )

    如果我犯了一个错误,比如拼错文件名,我会得到一个方便的错误:

    (node:17246) UnhandledPromiseRejectionWarning: Unhandled promise
    rejection. This error originated either by throwing inside of an async 
    function without a catch block, or by rejecting a promise which was not 
    handled with .catch(). (rejection id: 1)
    

    我可以通过这样做来解决:

    getFile('name').then( console.log ).catch( console.log ) 但是有没有一种方法来处理回调中的错误?也许是一次试一试?我该怎么做?

    2 回复  |  直到 6 年前
        1
  •  1
  •   kirbuchi    6 年前

    如果我理解正确,您希望您的函数能够解决问题,不管您是否得到错误。如果是这样,你可以 resolve 在任何一种情况下:

    async function getFile (name) {
      return new Promise(function (resolve, reject) {
        fs.readFile(`./dir/${name}.txt`, 'utf8', function (error, file) {
          if (error) resolve(error)
          else resolve(file)
        })
      })
    }
    

    然后你需要处理外部的错误,例如

    getFile('name')
      .then(getFileOutput => {
        if (getFileOutput instanceof Error) {
          // we got an error
        } else {
          // we got a file
        }
      })
    

    const getFileOutput = await getFile('name');
    if (getFileOutput instanceof Error) {
      // we got an error
    } else {
      // we got a file
    }
    

    这就是你要找的吗?

        2
  •  2
  •   Bergi    6 年前

    你仍然需要捕捉错误 rejected .

    我想这就是你所说的 getFile 函数来自-需要包装在 try/catch

    try {
      const result = await getFile('name')
    } catch(e) {
      ... You should see rejected errors here
    }
    

    或者,我认为这对您的示例是有效的:

    await getFile('name').then( console.log ).catch(e => {...})
    

    在chrome devtools控制台中测试:

    async function test () {
      return new Promise(function(resolve, reject) {
        throw 'this is an error';
      })
    }
    

    并通过以下方式调用它:

    await test().catch(e => alert(e))
    

    这表明,事实上,这是可行的!