| 1 | type Success<T> = { |
| 2 | data: T; |
| 3 | error: null; |
| 4 | }; |
| 5 | |
| 6 | type Failure<E> = { |
| 7 | data: null; |
| 8 | error: E; |
| 9 | }; |
| 10 | |
| 11 | type Result<T, E = Error> = Success<T> | Failure<E>; |
| 12 | |
| 13 | // Main wrapper function |
| 14 | export async function tryCatch<T, E = Error>( |
| 15 | promise: Promise<T>, |
| 16 | ): Promise<Result<T, E>> { |
| 17 | try { |
| 18 | const data = await promise; |
| 19 | return { data, error: null }; |
| 20 | } catch (error) { |
| 21 | return { data: null, error: error as E }; |
| 22 | } |
| 23 | } |