Last active
May 24, 2025 04:58
-
-
Save nthung2112/39649902bc1b02004faef435d9575dfb to your computer and use it in GitHub Desktop.
Error Try Catch
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
// /utils/result.ts | |
export type Failure<E> = { | |
success: false; | |
error: E; | |
}; | |
function Failure<E>(error: E): Failure<E> { | |
return { | |
success: false, | |
error, | |
}; | |
} | |
export type Success<T> = { | |
success: true; | |
value: T; | |
}; | |
function Success<T>(value: T): Success<T> { | |
return { | |
success: true, | |
value, | |
}; | |
} | |
export type Result<T, E = never> = Success<T> | Failure<E>; | |
export const Result = { | |
Failure, | |
Success, | |
}; |
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
export const tryCatch = async <T>( | |
fn: () => Promise<T>, | |
logError = false | |
): Promise<[T | undefined, Error | undefined]> => { | |
try { | |
const data = await fn(); | |
return [data, undefined]; | |
} catch (error: unknown) { | |
const err = error instanceof Error ? error : new Error(String(error)); | |
if (logError) { | |
console.error(err); | |
} | |
return [undefined, err]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment