An object containing either the data or the error.
export async function safeAsync<T>(
asyncFn: () => Promise<T>,
onError?: (error: AppError) => void,
): Promise<{ data: T | null; error: AppError | null }> {
try {
const data = await asyncFn();
return { data, error: null };
} catch (error) {
const appError = handleNetworkError(error);
if (onError) {
onError(appError);
}
return { data: null, error: appError };
}
}
Safely executes an async operation with error handling.