Skip to content

feat: implement transaction and error logging middleware with context…#89

Merged
Suhaibinator merged 5 commits intomainfrom
feature/handler-error-context
Jun 9, 2025
Merged

feat: implement transaction and error logging middleware with context…#89
Suhaibinator merged 5 commits intomainfrom
feature/handler-error-context

Conversation

@Suhaibinator
Copy link
Copy Markdown
Owner

@Suhaibinator Suhaibinator commented Jun 9, 2025

We successfully implemented the handler error context feature that allows middleware to access errors returned by generic route handlers. Here's what was added:

Changes Made:

  1. Updated SRouterContext (pkg/scontext/context.go):
    - Added HandlerError error field to store handler errors
    - Added HandlerErrorSet bool flag
    - Added helper functions: WithHandlerError(), GetHandlerError(), and GetHandlerErrorFromRequest()
  2. Modified Generic Route Handler (pkg/router/route.go):
    - Updated to store handler errors in context before calling handleError()
    - Ensures errors are available to all middleware in the chain
  3. Added Tests (pkg/scontext/handler_error_test.go and pkg/router/handler_error_test.go):
    - Tests for context error storage and retrieval
    - Tests for middleware access patterns
    - Tests for multiple middleware scenarios
  4. Created Example (examples/handler-error-middleware/main.go):
    - Demonstrates transaction middleware using handler errors
    - Shows custom error logging middleware
    - Examples of different error handling strategies

Benefits:

  • No Breaking Changes: Existing code continues to work without modification
  • Flexible: Middleware can make their own decisions based on handler errors
  • Clean API: Simple helper functions for setting and getting errors
  • Type-Safe: Uses the existing generic type system
  • Minimal Overhead: Only adds a single field to the context

This feature enables middleware authors to implement sophisticated error handling strategies without relying on response status codes or response writer wrappers.

@Suhaibinator Suhaibinator requested a review from Copilot June 9, 2025 01:12
Copy link
Copy Markdown
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 implements middleware enhancements to capture transaction and error logging details through context propagation. Key changes include:

  • Adding context fields and helper functions (WithHandlerError, GetHandlerError, GetHandlerErrorFromRequest) to store and retrieve handler errors.
  • Updating the generic route registration to insert handler errors into the request context.
  • Expanding test coverage and providing an example to demonstrate middleware-based transaction handling and error logging.

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pkg/scontext/handler_error_test.go Tests for setting, retrieving, and propagating handler errors
pkg/scontext/context.go Added error storage fields and functions to manage handler errors
pkg/router/route.go Updated route registration to capture handler errors in context
pkg/router/handler_error_test.go Added tests to verify error handling in generic routes and middleware
examples/handler-error-middleware/main.go Example demonstrating transaction and error logging middleware usage
Comments suppressed due to low confidence (1)

pkg/router/route.go:234

  • [nitpick] Consider adding a comment to note that this call overwrites any previously set handler error in the context, so that the middleware always retrieves the latest error.
ctx := scontext.WithHandlerError[UserID, User](req.Context(), err)

Comment thread pkg/scontext/context.go
Suhaibinator and others added 3 commits June 8, 2025 21:16
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…or/SRouter into feature/handler-error-context
@Suhaibinator Suhaibinator requested a review from Copilot June 9, 2025 01:45

This comment was marked as outdated.

@codecov
Copy link
Copy Markdown

codecov bot commented Jun 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.17%. Comparing base (1cbdacb) to head (16d5881).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main      #89   +/-   ##
=======================================
  Coverage   97.16%   97.17%           
=======================================
  Files          18       18           
  Lines        2363     2369    +6     
=======================================
+ Hits         2296     2302    +6     
  Misses         55       55           
  Partials       12       12           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Suhaibinator Suhaibinator requested a review from Copilot June 9, 2025 01:51
@Suhaibinator Suhaibinator merged commit 10158ca into main Jun 9, 2025
11 checks passed
Copy link
Copy Markdown
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

Implements support for storing handler-returned errors in the request context so that middleware (e.g., transaction management or custom error logging) can react after handler execution.

  • Adds HandlerError/HandlerErrorSet fields to SRouterContext with WithHandlerError and GetHandlerError… helpers
  • Updates the generic route handler to record errors in context before invoking handleError
  • Covers the feature with tests, an example application, and documentation updates

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pkg/scontext/context.go Added HandlerError & HandlerErrorSet fields and helper functions
pkg/scontext/handler_error_test.go Tests for setting/getting handler errors in context
pkg/router/route.go Records handler error in context when route.Handler returns an error
pkg/router/handler_error_test.go Tests that middleware sees errors stored during generic routing
examples/handler-error-middleware/main.go Example of transaction rollback & error-logging middleware using context
docs/middleware.md Added example snippet showing handler-error-driven middleware
docs/examples.md Listed new handler-error-middleware example
docs/error-handling.md Documented error context storage feature
docs/context-management.md Included WithHandlerError in list of context helper functions
CLAUDE.md Updated reference to GetHandlerErrorFromRequest in guidelines

Comment thread pkg/router/route.go
Comment on lines +234 to +237
// Note: We don't need to update req with the returned context because
// if SRouterContext already exists (which it should), this modifies
// the existing pointer that middleware already has access to
scontext.WithHandlerError[UserID, User](req.Context(), err)
Copy link

Copilot AI Jun 9, 2025

Choose a reason for hiding this comment

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

Explicitly assign the context returned by WithHandlerError back to the request (e.g., req = req.WithContext(scontext.WithHandlerError(...))) so that downstream middleware is guaranteed to see the updated context, rather than relying on pointer side effects.

Suggested change
// Note: We don't need to update req with the returned context because
// if SRouterContext already exists (which it should), this modifies
// the existing pointer that middleware already has access to
scontext.WithHandlerError[UserID, User](req.Context(), err)
// Explicitly assign the updated context back to the request to ensure downstream middleware sees it
req = req.WithContext(scontext.WithHandlerError[UserID, User](req.Context(), err))

Copilot uses AI. Check for mistakes.
@Suhaibinator Suhaibinator deleted the feature/handler-error-context branch June 9, 2025 01:53
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.

2 participants