Skip to content

A discussion about return type #199

@reboottime

Description

@reboottime

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');
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions