Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Oct 1, 2025

Summary

Simplifies error handling by replacing custom error classes with standard Error() + descriptive messages and context objects, reducing code complexity while maintaining clear error reporting.

Changes

Removed Custom Error Classes

Eliminated two custom error classes in src/modules/diet/macro-target/application/macroTarget.ts:

  • WeightNotFoundForDayError (26 lines)
  • MacroTargetNotFoundForDayError (26 lines)

These classes primarily added type complexity without runtime benefits. Their constructors, custom properties, and toJSON() methods are no longer needed.

New Pattern: Standard Error with Context

Before:

class WeightNotFoundForDayError extends Error {
  readonly day: Date
  readonly userId: User['uuid']
  readonly errorId: string
  
  constructor(day: Date, userId: User['uuid']) {
    super(`Peso não encontrado para o dia ${day.toISOString()}, usuário ${userId}`)
    this.name = 'WeightNotFoundForDayError'
    this.day = day
    this.userId = userId
    this.errorId = `weight-not-found-${userId}-${day.toISOString()}`
  }
  
  toJSON() { /* ... */ }
}

showError(new WeightNotFoundForDayError(day, userId), {})

After:

showError(
  new Error(`Peso não encontrado para o dia ${day.toISOString()}`, {
    cause: {
      day: day.toISOString(),
      userId,
      operation: 'getMacroTargetForDay',
      errorId: `weight-not-found-${userId}-${day.toISOString()}`,
    },
  }),
  {},
)

Documentation Updates

Updated docs/CODESTYLE_GUIDE.md to reflect the new standard:

  • Domain layer examples now use Error() with cause property
  • Removed references to custom error classes
  • Emphasized providing context via the cause property with relevant data (IDs, operation names)

Benefits

  • Simplified Codebase: Net reduction of 30 lines, removing unnecessary abstraction
  • Standard JavaScript: Uses built-in error handling patterns instead of custom classes
  • Maintained Context: Error context preserved via standard cause property
  • Better Alignment: Matches modern JavaScript/TypeScript error handling practices
  • Frontend Reality: Acknowledges that most errors come from network/API calls, not business logic violations

Testing

✅ All 368 tests passing
✅ Type checking passes
✅ Error handling infrastructure (showError) preserved and working
✅ Error messages remain descriptive and contextual
✅ No regression in user error experience

Rationale

This refactoring aligns with the project's frontend simplicity principles:

  • TypeScript provides compile-time safety - runtime errors should be simple
  • Users care about clear messages, not error taxonomies
  • Standard Error() + good error handling functions are sufficient
  • Reduces maintenance burden by avoiding unnecessary custom classes

Closes #[issue-number]

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • https://api.github.com/repos/marcuscastelo/macroflows/branches
    • Triggering command: curl -s REDACTED (http block)
  • https://api.github.com/repos/marcuscastelo/macroflows/compare/9a60ac53dfc707e5e0f49cd6cdaa3937d6a46fbf...fb134a2685842b898c47efcd934f8b89d957870f
    • Triggering command: curl -s -w \n%{http_code} -D /tmp/semver_headers_4013.txt REDACTED (http block)
  • test.supabase.co
    • Triggering command: node (vitest 1) (dns block)
    • Triggering command: node (vitest 3) (dns block)
    • Triggering command: node (vitest 2) (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>refactor: simplify error handling patterns for v0.17.0</issue_title>
<issue_description>## Summary

Simplify error handling patterns by replacing custom error classes with standard Error() + descriptive messages, while maintaining the essential handleApiError function for application-layer error management.

Current State

The codebase contains:

  • Custom error classes that mainly add type complexity without runtime benefits
  • Error hierarchies that could be simplified to standard errors
  • Good application-layer error handling with handleApiError (keep this!)

Proposed Changes

1. Simplify Error Classes

  • Replace custom error classes with standard Error() + descriptive messages
  • Use error context objects instead of error inheritance
  • Maintain clear error messages that include relevant context

2. Keep Essential Error Infrastructure

  • ✅ Maintain handleApiError function - provides real value for user feedback
  • ✅ Keep validation error handling patterns
  • ✅ Preserve error boundary functionality

3. Standard Error Patterns

// ✅ New pattern: Standard Error with context
throw new Error('Group mismatch: cannot mix different groups', { 
  cause: { groupId, recipeId, operation: 'validateGroupConsistency' } 
})

// ❌ Old pattern: Custom error class
throw new GroupConflictError(groupId, recipeId)

Rationale

Frontend Reality Check:

  • Most errors come from network/API calls, not business logic violations
  • Standard Error() + good error handling functions are sufficient
  • TypeScript provides compile-time safety - runtime errors should be simple
  • Users care about clear messages, not error taxonomies

Zod Integration:

  • Zod provides excellent validation without custom error classes
  • safeParse() patterns eliminate need for validation error hierarchies
  • Standard errors work well with Zod's error reporting

Implementation Strategy

Phase 1: Audit Current Error Classes

  • Identify all custom error classes in the codebase
  • Categorize by actual usage and benefit
  • Plan replacement with standard errors

Phase 2: Replace Custom Classes

  • Convert custom error classes to standard Error() calls
  • Update error handling to work with standard errors
  • Maintain error context through cause property

Phase 3: Preserve Application Layer

  • Keep handleApiError function intact
  • Maintain error boundary patterns
  • Ensure user feedback continues working

Testing

  • All error handling tests continue to pass
  • Error messages remain clear and helpful
  • Application-layer error management unchanged
  • pnpm check validates changes

Labels

  • refactor
  • complexity-medium
  • improvement

Acceptance Criteria

  • Custom error classes replaced with standard Error()
  • Error messages remain descriptive and contextual
  • handleApiError function preserved and working
  • All tests passing
  • No regression in user error experience
  • pnpm check passes</issue_description>

Comments on the Issue (you are @copilot in this section)

Fixes #984

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copy link

vercel bot commented Oct 1, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
macroflows Ready Ready Preview Comment Oct 1, 2025 1:19pm

Co-authored-by: marcuscastelo <27441558+marcuscastelo@users.noreply.github.com>
Co-authored-by: marcuscastelo <27441558+marcuscastelo@users.noreply.github.com>
@Copilot Copilot AI changed the title [WIP] refactor: simplify error handling patterns for v0.17.0 refactor: simplify error handling patterns - replace custom error classes with standard Error() Oct 1, 2025
Copilot finished work on behalf of marcuscastelo October 1, 2025 13:20
@Copilot Copilot AI requested a review from marcuscastelo October 1, 2025 13:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

refactor: simplify error handling patterns for v0.17.0
2 participants