Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A discussion about return type #199

Open
reboottime opened this issue Oct 30, 2024 · 0 comments
Open

A discussion about return type #199

reboottime opened this issue Oct 30, 2024 · 0 comments
Labels

Comments

@reboottime
Copy link
Owner

reboottime commented Oct 30, 2024

For large codebase

type Result<T, E = Error> = 
  | { success: true; data: T }
  | { success: false; error: E };

export const getSomething = async (
  supabase: SupabaseClient,
  hash: string
): Promise<Result<something>> => {
  const { data, error } = await supabase.rpc(`something`, {
    provided_hash: hash
  });
  
  if (error) {
    return { 
      success: false, 
      error: new Error(error.message)
    };
  }
  
  if (!data) {
    return {
      success: false,
      error: new Error("something not found")
    };
  }
  
  return { success: true, data };
};

Benefits

  • Predictable Error Handling:
    • No need to guess whether you need try/catch
    • Forces error handling at usage site
    • Clear separation between success and failure cases
  • Better of testing
test('handles not found case', async () => {
  const result = await getSomething(supabase, 'non-existent');
  expect(result.success).toBe(false);
  expect(result.error.message).toBe('Something not found');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant