繁体   English   中英

使用Async / Await进行自定义错误处理

[英]Custom Error Handling with Async/Await

老实说,我只是想知道我是否做对了。 如果我想要自定义错误消息,是否必须用try&catch包装每个异步函数?

以下代码的任何输入将不胜感激:

async function read(dir) {
  let paths, content;

  // read directory of paths to an array
  try {
    paths = await fs.readdir(dir);
  } catch(err) {
    throw 'Failed to read directory ' + dir;
  }

  // loop through paths reading file contents
  for(const file of paths) {
    try {
      content = await fs.readFile(file, 'utf-8');
    } catch(err) {
      throw 'Failed to read contents of ' + file;
    }

    try {

    // another async function that manipulates content

    } catch(err)
      throw 'Failed to do whatever';
    }
  }
  return content;
}

// a function down here that calls read and handles thrown errors.

这是一个完美的例子,说明异步/等待可以使代码更干净! 如果您不需要自定义错误消息,则只需使用一次try / catch。 但是因为这样做了,所以像您一样使用多个try / catching是可行的方法。 在for循环中使用await是最好的选择!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM