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...catchs 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
The question is not very clear but I'll try to answer it in the best possible way. For the pattern above, if you just want to return err in each one, you can have something like
If you have different implementation in each function of the error, you can have the syntax of .then and .catch there like above in each one.
If you are using NestJS you can take advantage of Exception Filters to get the context where error occur and handle it easily.
Not exactly but you can use a higher order function to get error handling as well.
What to use will depend on the use case. The one mentioned above can be cleaned by a lot of ways. Using TS class and filters, the code can be cleaned more. Moreover you can also write custom exception filters too but that might be an overkill. If you can explain your use case more then it be more helpful.