Seeking a more efficient approach, I aim to centralize all error handling in one global function instead of scattering try catch blocks everywhere. While appending await func().catch()
can capture errors, here is the global solution proposed:
async function errorhandler(func) {
try{
const result = await func();
return [result, null];
}catch (err) {
console.log(err);
return [null, err];
}
}
For implementation, consider using it as follows:
function mainFunction(){
const url = "https://jsonplaceholder.typicode.com/todos/"
const [data, error] = errorhandler(fetch(url));
if(error) //take necessary action
data. //missing method intellisense ?
}
mainFunction()
Unfortunately, this setup results in loss of autocompletion support. Attempts were made to introduce types, like so:
async function errorhandler(func: () => Promise<T>): any {
try{
const result = await func();
return [result, null];
}catch (err) {
console.log(err);
return [null, err];
}
}
function mainFunction(){
const url = "https://jsonplaceholder.typicode.com/todos/"
const [data, error]: any = errorhandler(() => fetch(url));
if(error) //take necessary action
data. //no intellisense
}
mainFunction()
Despite these efforts, the issue persists. Any insights or guidance on achieving autocomplete for data methods with type safety would be greatly appreciated.
The expectation is to have access to autocomplete suggestions for all available methods under the data field, ensuring type integrity.