0

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.
Danny I.
  • 57
  • 5

1 Answers1

2

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!

Alec Fenichel
  • 1,257
  • 1
  • 13
  • 27
  • Thanks for the input! Just wanted to make sure I was doing right; definitely much cleaner. – Danny I. Nov 05 '17 at 19:38
  • I don't see how this is any cleaner than using the promise `.catch(err => …)` syntax. Or what are you comparing it against? – Bergi Nov 05 '17 at 20:25
  • @Bergi The error handling isn't much cleaner, but it is a few less characters. The big difference is the await in the for loop, asynchronous for loops have always been a major pain until await. – Alec Fenichel Nov 05 '17 at 20:29
  • @AlecFenichel Actually the promise method is a few characters and two lines shorter: `try { content = await …; } catch(err) { throw …; }` vs `content = await ….catch(err => { throw …; });`. I think not assigning to `content` inside a block [even is cleaner](https://stackoverflow.com/a/44664037/1048572) than having to nest it. – Bergi Nov 05 '17 at 22:18
  • @Bergi I was refering to using promises before the await/async construct was available. I was not intending to compare the use of promises and try/catch with async/await. – Alec Fenichel Nov 05 '17 at 22:43
  • But that's what the OP is asking about, isn't he? – Bergi Nov 05 '17 at 22:53
  • I don't think so. The title "Custom Error Handling with Async/Await" has nothing to do with try/catch but async/await. I think the OP is accustomed to writing code with callbacks not async/await and wanted to confirm he was doing it correctly. I just went through this change ~6 months ago, it takes some getting used to but it is a great new design. – Alec Fenichel Nov 05 '17 at 23:01