Skip to content

feat: add Fastify global setErrorHandler#122

Open
2witstudios wants to merge 3 commits intomainfrom
ppg/issue-87-global-error
Open

feat: add Fastify global setErrorHandler#122
2witstudios wants to merge 3 commits intomainfrom
ppg/issue-87-global-error

Conversation

@2witstudios
Copy link
Owner

@2witstudios 2witstudios commented Feb 27, 2026

Summary

  • Adds a Fastify plugin (src/server/error-handler.ts) that registers a global setErrorHandler as a safety net for unhandled route errors
  • PpgError instances map to their code and message with appropriate HTTP status
  • Validation errors return { error: { code: "VALIDATION_ERROR", message } }
  • Unexpected errors return { error: { code: "INTERNAL_ERROR", message } } — stack traces and internal details are suppressed in production (NODE_ENV=production)
  • Uses fastify-plugin (via fp()) so the handler is registered at the root scope, not encapsulated

Test plan

  • 9 tests covering PpgError, validation errors, unhandled errors (prod + dev), status code preservation, and JSON content-type
  • npm test passes
  • Verify integration with other Fastify server scaffold PRs once merged

Closes #87

Summary by CodeRabbit

  • New Features

    • Implemented a new error handling system with structured error responses, HTTP status code mapping for custom error codes, and validation error handling with environment-specific message obfuscation.
  • Tests

    • Added comprehensive test suite covering error handling across multiple scenarios, including status code mapping, validation errors, and environment-specific behavior.
  • Chores

    • Added Fastify framework and plugin dependencies.

Register a Fastify plugin that catches unhandled route errors and
returns structured JSON responses. PpgErrors map to their code/message,
validation errors return VALIDATION_ERROR, and unexpected errors return
INTERNAL_ERROR without leaking stack traces in production.

Closes #87
@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

Warning

Rate limit exceeded

@2witstudios has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 10 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f250caa and dae3278.

📒 Files selected for processing (1)
  • src/commands/spawn.test.ts
📝 Walkthrough

Walkthrough

This PR introduces a centralized error handling module for Fastify that registers a global error handler plugin. It implements HTTP status mapping for custom error codes, distinguishes between PpgError, validation errors, and unhandled errors, and provides environment-aware error responses. Two new Fastify dependencies have been added to support this functionality.

Changes

Cohort / File(s) Summary
Dependencies
package.json
Added Fastify 5.7.4 and fastify-plugin 5.1.0 dependencies.
Error Handler Implementation
src/server/error-handler.ts
Introduced ErrorResponseBody interface, httpStatusForPpgError function for mapping custom error codes to HTTP statuses, errorHandler function handling PpgError/validation/unhandled errors, and a Fastify plugin export for global error registration.
Error Handler Tests
src/server/error-handler.test.ts
Comprehensive test suite validating HTTP status mappings for specific error codes, validation error handling (400 responses), environment-specific unhandled error behavior (obfuscated in production), statusCode preservation, and content-type headers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

  • Issue #87: The implementation directly fulfills the acceptance criteria for adding a Fastify global setErrorHandler, including structured JSON error responses, error logging, production-safe message handling, and comprehensive test coverage.

Poem

🐰 With whiskers twitched, the errors fly,
No more shall bad requests pass by,
A handler catches them with care,
Formats responses, clean and fair,
In JSON's nest, safe they rest! 🏠

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat: add Fastify global setErrorHandler' clearly and specifically describes the main change: implementing a global error handler for Fastify.
Description check ✅ Passed The description covers all required sections: What (adds error-handler plugin), Why (safety net), How (implementation details), and Checklist items addressing testing and code quality.
Linked Issues check ✅ Passed The PR fulfills all acceptance criteria from #87: registers setErrorHandler, logs errors, returns structured JSON responses, suppresses production details, includes comprehensive tests, and handles PpgError/validation errors.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #87: new error-handler plugin with tests and package.json dependencies; no unrelated modifications present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ppg/issue-87-global-error

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

- P1: Replace exitCode-as-HTTP-status with explicit code-to-status
  lookup map (httpStatusByCode). PpgError.exitCode is a CLI concept,
  not an HTTP one — WORKTREE_NOT_FOUND→404, MANIFEST_LOCK→409, etc.
- P2: Remove unused vi import, use vi.stubEnv for safe env mutation
  in tests with vi.unstubAllEnvs in afterEach
- P2: Add await app.ready() before inject in all tests
- P3: Fix test naming to follow 'given X, should Y' convention
- P3: Add async route handler test case
- Add httpStatusForPpgError unit tests for lookup table coverage
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 Fastify global setErrorHandler

1 participant