This is a fairly simple bit of code:
async function fetchData() {
console.log("fetching data");
let json;
try {
const data = await fetch(endPoint);
json = await data.json();
}
catch (error) {
console.error(error);
handleError(error);
}
try {
await saveData(json);
} catch (error) {
console.error(error);
handleError(error);
}
}
console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");
What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.
So there's two main kinds of errors we might get here:
- The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.
- The database might return some kind of error. For all the same reasons, but a completely different service.
Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.
But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different try
catch
blocks, that gives me the flexibility to handle them differently.
But it does look a bit messier, in my opinion. The other way I could write this is:
async function fetchData() {
console.log("fetching data");
try {
const data = await fetch(endPoint);
const json = await data.json();
await saveData(json);
}
catch (error) {
console.error(error);
handleError(error);
}
}
console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");
This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.
I guess I could put a switch
statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?