Skip to content

Instantly share code, notes, and snippets.

@huynhducduy
Last active February 28, 2025 10:42
Show Gist options
  • Save huynhducduy/d9967ae5324707db72d276cdfc69c82c to your computer and use it in GitHub Desktop.
Save huynhducduy/d9967ae5324707db72d276cdfc69c82c to your computer and use it in GitHub Desktop.
tryCatch.ts
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}}
}
}
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