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

Javascript 使用Async/Await自定义错误处理,javascript,error-handling,async-await,Javascript,Error Handling,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 dire

老实说,我只是想知道我做得对不对。如果需要自定义错误消息,是否必须用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.

这是一个很好的例子,说明async/await可以让代码变得更干净!如果您不需要自定义错误消息,那么您可以只使用一个try/catch。但是因为你这样做了,所以像你那样使用多个try/catch是一种方法。在for循环中使用wait是有史以来最好的事情

这是一个很好的例子,说明async/await可以让代码变得更干净!如果您不需要自定义错误消息,那么您可以只使用一个try/catch。但是因为你这样做了,所以像你那样使用多个try/catch是一种方法。在for循环中使用wait是有史以来最好的事情

如果你想为每个步骤定制错误消息,你必须在每个步骤捕获默认错误。你的
fs
方法真的返回承诺吗?是的,我使用fs extra()。如果你想为每个步骤定制错误消息,你必须在每个步骤捕获默认错误。你的
fs
方法真的返回承诺吗?是的,我正在使用fs extra()。感谢您的输入!只是想确定我做得对;肯定要干净得多。我看不出这比使用promise
.catch(err=>…)
语法更干净。或者你将它与什么进行比较?@Bergi错误处理不是很干净,但它少了几个字符。最大的区别是for循环中的wait,异步for循环在wait之前一直是一个主要的痛苦。@AlecFenichel实际上promise方法只有几个字符,短了两行:
try{content=wait…;}catch(err){throw…;}
vs
content=wait…catch(err=>{throw…;})。我认为不在块内分配
内容
比嵌套它更重要。@Bergi我指的是在wait/async构造可用之前使用承诺。我无意将Promissions和try/catch与async/await的用法进行比较。谢谢您的输入!只是想确定我做得对;肯定要干净得多。我看不出这比使用promise
.catch(err=>…)
语法更干净。或者你将它与什么进行比较?@Bergi错误处理不是很干净,但它少了几个字符。最大的区别是for循环中的wait,异步for循环在wait之前一直是一个主要的痛苦。@AlecFenichel实际上promise方法只有几个字符,短了两行:
try{content=wait…;}catch(err){throw…;}
vs
content=wait…catch(err=>{throw…;})。我认为不在块内分配
内容
比嵌套它更重要。@Bergi我指的是在wait/async构造可用之前使用承诺。我并不打算将承诺和try/catch与async/await进行比较。