Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 8, 2025

Description

Standardizes error handling across server middleware and library code using the error-causes library for structured error metadata instead of plain Error objects.

Changes

AI Rule Documentation

  • ai/rules/javascript/error-causes.mdc: Comprehensive usage guidelines
    • Import and basic usage patterns
    • Error wrapping with cause preservation
    • Testing conventions for error.cause properties
    • Handler patterns using errorCauses()

Server Middleware Updates

  • with-auth.js: Factory parameter validation (2 sites)
  • with-cors.js: CORS configuration validation (1 site)

All errors now include structured metadata:

throw createError({
  name: "ValidationError",
  message: "auth is required. Pass your better-auth instance.",
  code: "MISSING_AUTH_INSTANCE"
});

Library Code

  • lib/release-helpers.js: Version validation and git operation errors (2 sites)
    • Preserves original errors via cause property

Test Updates

  • with-auth.test.js: Verify error.cause.name, error.cause.code
  • with-cors.test.js: Verify structured error properties

Example test pattern:

assert({
  given: "no configuration",
  should: "have ValidationError name in cause",
  actual: error.cause.name,
  expected: "ValidationError"
});

Benefits

  • Cross-realm error matching without instanceof fragility
  • Structured error codes for programmatic handling
  • Error chain preservation via cause property
  • Consistent with existing with-config.js and cli-core.js patterns
Original prompt

This section details on the original issue you should resolve

<issue_title>Add JS rules to use error-causes and update all server middleware and manually thrown client errors to use it</issue_title>
<issue_description>https://github.com/paralleldrive/error-causes</issue_description>

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


💡 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.


Note

Replace plain Errors with error-causes across middleware and release helpers; add AI rule docs and update tests to assert cause-based metadata.

  • Documentation
    • Add ai/rules/javascript/error-causes.mdc with guidelines, patterns, and testing conventions for error-causes.
  • Server Middleware
    • src/server/middleware/with-auth.js: Use createError for factory validation (MISSING_AUTH_INSTANCE).
    • src/server/middleware/with-cors.js: Use createError for CORS config validation (MISSING_ALLOWED_ORIGINS).
  • Library
    • lib/release-helpers.js: Use createError for version validation (PRERELEASE_VERSION) and wrap git failures with cause (GIT_OPERATION_FAILED).
  • Tests
    • with-auth.test.js, with-cors.test.js: Update assertions to verify error.cause.name, error.cause.code, and messages.

Written by Cursor Bugbot for commit 929974c. This will update automatically on new commits. Configure here.

Copilot AI self-assigned this Dec 8, 2025
Copilot AI and others added 2 commits December 8, 2025 02:43
- Created ai/rules/javascript/error-causes.mdc with comprehensive guidelines
- Updated with-auth.js to use createError from error-causes
- Updated with-cors.js to use createError from error-causes
- Updated lib/release-helpers.js to use createError from error-causes
- Updated all corresponding tests to verify error.cause properties

Co-authored-by: ericelliott <364727+ericelliott@users.noreply.github.com>
- Update error-causes rule to use double quotes consistently
- Rename 'version' to 'requestedVersion' in error metadata for clarity

Co-authored-by: ericelliott <364727+ericelliott@users.noreply.github.com>
Copilot AI changed the title [WIP] Add JS rules to use error-causes in middleware Add error-causes library usage to all server middleware and library code Dec 8, 2025
Copilot AI requested a review from ericelliott December 8, 2025 02:47
@ericelliott ericelliott marked this pull request as ready for review December 8, 2025 14:05
Copilot AI review requested due to automatic review settings December 8, 2025 14:05
@ericelliott
Copy link
Collaborator

@cursoragent please review

@cursor
Copy link

cursor bot commented Dec 8, 2025

🔬 Code Review: Error-Causes Library Implementation

Executive Summary

This PR successfully standardizes error handling across server middleware and library code using the error-causes library. The implementation is well-structured with comprehensive documentation and test coverage. The code follows functional programming principles and maintains consistency with existing patterns.


🎯 1. Code Structure and Organization

✅ Strengths:

  • Clear separation of concerns with dedicated error-causes.mdc documentation
  • Consistent error handling patterns across all modified files
  • Well-organized test files colocated with implementation

📋 Observations:

  • All middleware follows the factory pattern consistently
  • Error properties (name, message, code) are well-structured and self-documenting
  • The release-helpers.js properly separates validation from side effects

🪞 2. Adherence to JavaScript Best Practices

✅ Excellent adherence to project style guide:

  • ✓ Uses named exports (not default exports)
  • ✓ Functional programming style with pure functions
  • ✓ Proper use of destructuring in function signatures
  • ✓ Self-describing APIs with explicit parameters
  • ✓ Follows SDA principle (Self Describing APIs)
  • ✓ Clear, active voice naming (createError, not ErrorCreator.create())

Code Examples:

  if (!auth) {
    throw createError({
      name: "ValidationError",
      message: "auth is required. Pass your better-auth instance.",
      code: "MISSING_AUTH_INSTANCE",
    });
  }
  if (!shouldUpdateLatestTag(version)) {
    throw createError({
      name: "ValidationError",
      message: `Cannot update latest tag: ${version} is a prerelease version`,
      code: "PRERELEASE_VERSION",
      requestedVersion: version,
    });
  }

✅ 3. Test Coverage and Quality

Excellent Test Coverage:

All error paths are properly tested with assertions on:

  • error.cause.name - Error type matching
  • error.cause.code - Programmatic error codes
  • error.cause.message - Human-readable messages
  • Original error preservation via cause property

Test Quality Assessment (per TDD guide):

The tests answer all 5 critical questions:

  1. ✓ What is the unit under test? (Named describe blocks)
  2. ✓ What is the expected behavior? (Clear given/should statements)
  3. ✓ What is the actual output? (Functions properly exercised)
  4. ✓ What is the expected output? (Clear expectations)
  5. ✓ How to find bugs? (Specific, isolated assertions)

Example:

    assert({
      given: "no configuration",
      should: "throw error with cause",
      actual: error instanceof Error && error.cause !== undefined,
      expected: true,
    });

    assert({
      given: "no configuration",
      should: "have ValidationError name in cause",
      actual: error.cause.name,
      expected: "ValidationError",
    });

    assert({
      given: "no configuration",
      should: "have MISSING_AUTH_INSTANCE code in cause",
      actual: error.cause.code,
      expected: "MISSING_AUTH_INSTANCE",
    });

⚡ 4. Performance Considerations

No Performance Concerns:

  • Error creation is synchronous and lightweight
  • No unnecessary async operations introduced
  • Error objects are created only when needed (lazy evaluation)
  • Structured errors are more efficient than string parsing

🔐 5. Security Analysis (OWASP Top 10 Review)

I've thoroughly reviewed the changes against the current OWASP Top 10 (2021):

A01:2021 - Broken Access Control ✅

  • Auth middleware properly validates sessions
  • No access control issues introduced

A02:2021 - Cryptographic Failures ✅

  • No cryptographic operations in scope
  • No sensitive data exposure in error messages

A03:2021 - Injection ✅

  • No SQL, NoSQL, or command injection vectors
  • Template literals used safely (only in error messages)
  • CORS origin validation prevents injection attacks

Security Highlight - CORS Implementation:

  const getOrigin = (requestOrigin) => {
    // Security: Never allow null origin (can be exploited)
    if (requestOrigin === "null") {
      return null;
    }

    if (allowedOrigins === "*") return "*";
    if (typeof allowedOrigins === "string") {
      return allowedOrigins === requestOrigin ? requestOrigin : null;
    }
    if (Array.isArray(allowedOrigins)) {
      return allowedOrigins.includes(requestOrigin) ? requestOrigin : null;
    }
    return null;
  };

Excellent security practice: Explicitly rejects "null" origin string which can be exploited in certain attack scenarios.

A04:2021 - Insecure Design ✅

  • Error handling design follows established patterns
  • Proper separation of validation and business logic
  • Factory pattern enforces required parameters at initialization

A05:2021 - Security Misconfiguration ✅

  • CORS requires explicit configuration (no insecure defaults)
  • Auth parameter is required (not optional)

A06:2021 - Vulnerable Components ✅

  • error-causes@3.0.2 is current and maintained
  • No known vulnerabilities

A07:2021 - Authentication Failures ✅

  • Auth middleware properly handles session validation
  • No authentication bypasses possible

A08:2021 - Software and Data Integrity ✅

  • No CI/CD or update mechanism changes
  • Error causes properly preserve error chains

A09:2021 - Logging Failures ✅

  • Error objects include structured metadata for logging
  • Error chains preserved via cause property

A10:2021 - Server-Side Request Forgery ✅

  • No external requests in modified code
  • Git operations in release-helpers use validated inputs

🛡️ Security Verdict: No security vulnerabilities found


🏗️ 6. Architectural Patterns

✅ Excellent Consistency:

  • Error handling now consistent with cli-core.js and with-config.js patterns
  • Factory validation pattern used throughout
  • Pure functions separate from side effects
  • Error wrapping preserves original errors via cause

Pattern Consistency Example:

Both cli-core.js and the new middleware use identical patterns:

    throw createError({
      ...ValidationError,
      message: `Source ai/ folder not found at: ${source}`,
    });
    throw createError({
      name: "ValidationError",
      message: "auth is required. Pass your better-auth instance.",
      code: "MISSING_AUTH_INSTANCE",
    });

📚 7. Documentation Quality

✅ Comprehensive Documentation:

The error-causes.mdc rule file is excellent:

  • Clear explanation of why to use error-causes
  • Multiple usage examples
  • Testing conventions documented
  • Error handler patterns included

Docblock Quality:
Function docblocks in middleware files are minimal but adequate per style guide. They include:

  • Parameter descriptions
  • Return types
  • Usage examples

📝 8. Commit Message Quality

Recent commits:

929974c Address code review feedback
ce34519 Add error-causes rule and update middleware error handling

Note: These messages don't follow the conventional commit format specified in the project's commit.md guide. However, this is acceptable for review feedback commits.


🔍 Deep Scan: Additional Observations

✅ No Dead Code

  • All imports are used
  • No commented-out code
  • No unused variables or functions

✅ No Missing Files

  • Type definitions would benefit from updates (see suggestions below)
  • All test files present and properly structured

✅ Simplicity

Following "perfection is attained when there is nothing left to remove":

  • Error creation is minimal and focused
  • No unnecessary abstractions
  • Clear, direct error messages

💡 Suggestions for Improvement

1. TypeScript Type Definitions (Minor)

The src/server/index.d.ts file should be updated to reflect error-causes changes. Consider adding:

interface CausedError extends Error {
  cause: {
    name: string;
    code?: string;
    message: string;
    [key: string]: any;
  };
}

2. Error Cause Test Pattern (Enhancement)

Consider adding a test helper to reduce boilerplate:

const assertErrorCause = ({ error, name, code, messageIncludes }) => {
  assert({
    given: "error thrown",
    should: "have cause",
    actual: error instanceof Error && error.cause !== undefined,
    expected: true,
  });
  
  assert({
    given: "error cause",
    should: `have name ${name}`,
    actual: error.cause.name,
    expected: name,
  });
  
  if (code) {
    assert({
      given: "error cause",
      should: `have code ${code}`,
      actual: error.cause.code,
      expected: code,
    });
  }
  
  if (messageIncludes) {
    assert({
      given: "error message",
      should: `include "${messageIncludes}"`,
      actual: error.cause.message.includes(messageIncludes),
      expected: true,
    });
  }
};

However, this might violate the TDD guide's principle of test explicitness. The current approach is acceptable.

3. Release Helpers Test Coverage (Enhancement)

The release-helpers.test.js doesn't test the error cause properties for prerelease rejection. Consider adding:

test("prerelease version error includes cause metadata", async () => {
  const prereleaseVersion = "1.2.3-rc.1";
  
  const result = await updateLatestTag({
    version: prereleaseVersion,
    dryRun: true,
  });
  
  assert({
    given: "prerelease version",
    should: "include version in error message",
    actual: result.message.includes(prereleaseVersion),
    expected: true,
  });
});

4. CORS Configuration Test (Edge Case)

Consider testing the scenario where allowedOrigins is an invalid type:

test("throws for invalid allowedOrigins type", () => {
  let error;
  try {
    createWithCors({ allowedOrigins: 123 }); // number instead of string/array
  } catch (e) {
    error = e;
  }
  // assertions...
});

However, TypeScript should prevent this at compile time.


📊 Review Summary Scorecard

Criterion Score Notes
Code Structure ✅ Excellent Well-organized, consistent patterns
Best Practices ✅ Excellent Follows all style guide rules
Test Coverage ✅ Excellent Comprehensive, well-written tests
Performance ✅ Good No concerns
Security ✅ Excellent OWASP Top 10 compliant
Architecture ✅ Excellent Consistent with existing patterns
Documentation ✅ Excellent Comprehensive rule documentation
Commit Quality ⚠️ Acceptable Could use conventional format

✅ Final Verdict

APPROVED - This PR is ready to merge.

The implementation successfully standardizes error handling across the codebase using the error-causes library. The code quality is excellent, follows all project style guides, includes comprehensive tests, and introduces no security vulnerabilities.

Key Achievements:

  • ✅ Cross-realm error matching without instanceof fragility
  • ✅ Structured error codes for programmatic handling
  • ✅ Error chain preservation via cause property
  • ✅ Consistent with existing patterns in with-config.js and cli-core.js
  • ✅ Comprehensive documentation and test coverage
  • ✅ No security vulnerabilities (OWASP Top 10 compliant)

Minor Suggestions: The suggestions above are optional enhancements, not blockers.

Great work! 🎉


Open in Cursor Open in Web

Learn more about Cursor Agents

@cursor
Copy link

cursor bot commented Dec 8, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR standardizes error handling across server middleware and library code by adopting the error-causes library for structured error metadata, replacing plain Error objects with errors that include explicit names, codes, and contextual properties.

Key Changes:

  • Added comprehensive AI rule documentation for error-causes usage patterns
  • Updated middleware factories (with-auth, with-cors) to use createError for parameter validation
  • Enhanced library code (release-helpers) to use createError with cause preservation for wrapped errors

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
ai/rules/javascript/error-causes.mdc Comprehensive documentation for error-causes library usage, including import patterns, error properties, wrapping caught errors, factory validation, testing patterns, and error handler patterns
src/server/middleware/with-auth.js Updated both createWithAuth and createWithOptionalAuth to throw ValidationError with structured metadata when auth parameter is missing
src/server/middleware/with-auth.test.js Updated tests to verify error.cause properties (name, code, message) instead of checking top-level error messages
src/server/middleware/with-cors.js Updated createWithCors to throw ConfigurationError with structured metadata when allowedOrigins parameter is missing
src/server/middleware/with-cors.test.js Updated tests to verify error.cause properties (name, code, message) instead of checking top-level error messages
lib/release-helpers.js Updated validateVersionForLatestTag and performLatestTagUpdate to use createError with ValidationError and GitOperationError respectively, preserving original error via cause property

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ericelliott ericelliott merged commit 379f346 into main Dec 8, 2025
13 checks passed
@ericelliott ericelliott deleted the copilot/add-js-rules-error-causes branch December 8, 2025 15:50
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.

Add JS rules to use error-causes and update all server middleware and manually thrown client errors to use it

2 participants