Danny I.
Danny I.

Reputation: 57

Custom Error Handling with Async/Await

Honestly, I'm just wondering if I'm doing this right. If I want custom error messages, do I have to wrap every single async function with a try & catch?

Any input on the following code would be extremely appreciated:

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.

Upvotes: 0

Views: 1009

Answers (1)

Alec Fenichel
Alec Fenichel

Reputation: 1317

This is a perfect example of how much cleaner async/await can make your code! If you don't need custom error messages, then you can just use one try/catch. But because you do, using multiple try/catches like you did is the way to go. Using await in a for loop is the best thing ever!

Upvotes: 2

Related Questions