Created
November 21, 2024 06:37
-
-
Save levchenkod/a54c599fd7f8d54d1ba50f66cd0125f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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