Skip to content

Instantly share code, notes, and snippets.

@levchenkod
Created November 21, 2024 06:37
Show Gist options
  • Save levchenkod/a54c599fd7f8d54d1ba50f66cd0125f1 to your computer and use it in GitHub Desktop.
Save levchenkod/a54c599fd7f8d54d1ba50f66cd0125f1 to your computer and use it in GitHub Desktop.
//https://www.youtube.com/watch?v=AdmGHwvgaVs&t=414s
const catchErrorTyped = <T, E extends new (message?: string) =>
Error>(
p: Promise<T>,
customErrors?: E[]
):Promise<(undefined| T)[] | [E]> => {
return p.then((data:T) => {
return [undefined, data];
})
.catch((error) => {
if(customErrors === undefined) {
return [error];
}
if(customErrors.some(e => error instanceof e)){
return [error];
}
throw error;
})
}
const randomErrorAsync = () => new Promise((resolve, reject) => {
const isError = Math.round(Math.random()) > 0;
// uncomment for test
// asd;
setTimeout(isError ? () => reject(new RandomError()) : () => resolve('ok'), 1000);
});
class RandomError extends Error {
name = 'RandomError'
}
(async function(){
const [error, happyMessage] = await catchErrorTyped(randomErrorAsync(), [RandomError]);
if(error){
console.error(error);
} else {
console.info(happyMessage);
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment