66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
/**
|
|
* Result Utility
|
|
*
|
|
* Go-style error handling utilities for safer, more explicit error handling.
|
|
* Provides Result type and tryCatch wrappers to eliminate try-catch boilerplate.
|
|
*/
|
|
|
|
/**
|
|
* Go-style Result type for explicit error handling
|
|
* Returns [data, null] on success or [null, error] on failure
|
|
*
|
|
* @example
|
|
* const [data, error] = tryCatch(() => riskyOperation());
|
|
* if (error) {
|
|
* // Handle error
|
|
* return;
|
|
* }
|
|
* // Use data safely
|
|
*/
|
|
export type Result<T, E = Error> = [T, null] | [null, E];
|
|
|
|
/**
|
|
* Wraps a function in try-catch and returns Result tuple
|
|
* Similar to Go's (value, error) pattern
|
|
*
|
|
* @param fn Function to execute
|
|
* @returns Tuple of [result, null] or [null, error]
|
|
*/
|
|
export function tryCatch<T>(fn: () => T): Result<T> {
|
|
try {
|
|
const result = fn();
|
|
return [result, null];
|
|
} catch (error) {
|
|
return [null, error instanceof Error ? error : new Error(String(error))];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Async version of tryCatch for promises
|
|
*
|
|
* @param fn Async function to execute
|
|
* @returns Promise resolving to tuple of [result, null] or [null, error]
|
|
*/
|
|
export async function tryCatchAsync<T>(fn: () => Promise<T>): Promise<Result<T>> {
|
|
try {
|
|
const result = await fn();
|
|
return [result, null];
|
|
} catch (error) {
|
|
return [null, error instanceof Error ? error : new Error(String(error))];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Safely executes a void function, ignoring any errors
|
|
* Perfect for cleanup operations like unsubscribe where errors don't matter
|
|
*
|
|
* @param fn Function to execute safely
|
|
*/
|
|
export function safely(fn: () => void): void {
|
|
try {
|
|
fn();
|
|
} catch {
|
|
/* Ignore errors during cleanup */
|
|
}
|
|
}
|