Last active
February 28, 2025 10:42
-
-
Save huynhducduy/d9967ae5324707db72d276cdfc69c82c to your computer and use it in GitHub Desktop.
tryCatch.ts
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
interface Success<T> { | |
result: T | |
exception?: never | |
} | |
interface Failure { | |
result?: never | |
exception: {getError: () => unknown} | |
} | |
type TryCatchResult<T> = Success<T> | Failure | |
export default async function tryCatch<T>(fn: (() => T) | Promise<T>): Promise<TryCatchResult<T>> { | |
try { | |
const result = typeof fn === 'function' ? fn() : await fn | |
return {result} | |
} catch (error) { | |
return {exception: {getError: () => error}} | |
} | |
} |
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
const {result, exception} = await tryCatch(fetch()) | |
if (exception) { | |
const error = exception.getError() | |
if (isValidationError(error)) { | |
return { | |
success: false, | |
issues: error.issues | |
} | |
} | |
console.error(error) | |
throw new Error('Unexpected error, please try again!') | |
} | |
return { | |
success: true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment