This code is ugly, isn't it?
import axios from 'axios';
async function f1() {
try {
const resp = await axios.get('http://www.randomnumberapi.com/api/v1.0/randomnumber');
return resp.data[0];
} catch (err) {
throw err;
}
}
async function f2() {
try {
return 1 + (await f1());
} catch (err) {
throw err;
}
}
async function main() {
try {
return 1 + (await f2());
} catch (err) {
throw err;
}
}
try {
console.log(await main());
} catch (err) {
throw err;
}
But it seems, I have no way to write it in a different way. Because each await
requires the try...catch
. Otherwise I have the Unhandled promise rejection
error. But too many try...catch
s make the code not so nice.
Is there an approach how to make this code like nicer?
Note 1: I'm using Nest.js if it helps for the good answer. Note 2: I've looked at such answers, but they are slightly about different: How to avoid using try...catch blocks Removing excessive try-catch blocks Too many try/catch blocks. Is this proper? bad try catch block design? Try catch block in express