Hacker News new | past | comments | ask | show | jobs | submit login

Personally - he's trying to shove the logic to catch the error into the wrong place.

The loop isn't the right spot to be catching an error that resulted from failing to fetch the data, or to parse the json data that was returned. The right spot was right there at the top of the file...

    const chapterPromises = chapterURLs.map(async (url) => {
      const response = await fetch(url);
      return response.json();
    });
This is where the error is occuring, and this is also the only reasonable spot to handle it. A very simple change to

    const chapterPromises = chapterURLs.map(async (url) => {
      try {
        const response = await fetch(url);
        return response.json();
      } catch(err) {
        // Optionally - Log this somewhere...
        return `Failed to fetch chapter data from ${url}` // Or whatever object appendChapter() expects with this as the content.
      }
    });
Solves the entire issue.



That means you'll display chapter 3 even if chapter 2 fails, rather than explain that the story has failed to load. There's no point showing additional chapters if an earlier one fails.


Now you're pretty far out of a discussion about handling promise rejections, and into a discussion about product UX and feature design...

"There's no point showing additional chapters if an earlier one fails." <- This is not always true, and heavily dependent on what the use case is. For a book? sure. for a manual or textbook? Much less sure.

The approach works just fine either way, though - if you don't want to display additional chapters if one fails, you can do so easily by just including a "success" field (or anything similar) in the object that appendChapters expects, and break if needed when you hit that. (although again - you'd probably be better served by displaying a user readable error and offering a button to retry, and then displaying the rest of the content so you don't have to fetch it all a second time).

Alternatively, you can also have appendChapters throw, or if you really want, you can still leave the promise rejection - but leaving the rejection or throwing at this spot means you're making a contract that calls for `try/catch` to use without unhandled rejections.

That's the whole deal with async await. You're trading the formatting of .then().catch() for try{}catch(){}.

if you don't like writing try/catch blocks, either structure the contract so that the promise doesn't reject (at least for expected error cases), or use the traditional .then().catch().




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: