Skip to content

Conversation

@gmorales96
Copy link
Contributor

@gmorales96 gmorales96 commented Oct 16, 2025

Summary by CodeRabbit

  • New Features

    • Logs and API error responses now include explicit, human-readable error details alongside status codes for failed requests.
  • Tests

    • Tests updated to assert consistency between logged data and actual responses, including error messages and status codes across several failure scenarios.
  • Chores

    • Package version bumped to 1.5.2.

@coderabbitai
Copy link

coderabbitai bot commented Oct 16, 2025

Walkthrough

Replaced get_status_code_exception(exc: Exception) -> int with get_exception_status_and_detail(exc: Exception) -> tuple[int, str] in agave/fastapi/middlewares/loggin_route.py. The new helper returns both an HTTP status code and an error detail string for various exception types (HTTPException, RequestValidationError, AgaveError, CuencaError, default). LoggingRoute exception handling now unpacks (status_code, error_detail) and records log_data['response'] with both status_code and error. Bumped __version__ from 1.5.1 to 1.5.2. Tests in tests/fastapi/test_loggin_route.py were updated to parse and compare logged response['error'], assert request body equality, and ensure logged status_code matches actual responses; new imports ast and json were added.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Feat/fastapi loggin route error detail" directly reflects the main objective of the changeset. The primary modification refactors the exception handling in the logging route middleware to capture and return error details alongside status codes, then updates the logging logic to record these details in the response log data. The title accurately conveys this enhancement by specifically mentioning "fastapi loggin route" and "error detail," making it clear to reviewers scanning the history that this PR adds error detail logging capabilities to the middleware. The title is concise, descriptive, and free of vague terminology.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/fastapi-loggin-route-error-detail

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
agave/fastapi/middlewares/loggin_route.py (1)

31-40: Consider consolidating with get_status_code_exception to reduce duplication.

The new get_error_detail function mirrors the structure of get_status_code_exception (lines 19-28), checking the same exception types in the same order. While each function has a clear single responsibility, consider refactoring to reduce the duplicated conditional logic.

For example, you could create a generic helper that takes a mapping of exception types to attribute extractors, or combine both functions into a single one that returns a tuple.

Current implementation is correct and functional, so this refactor can be deferred.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03ce8c7 and c4e8e50.

📒 Files selected for processing (3)
  • agave/fastapi/middlewares/loggin_route.py (2 hunks)
  • agave/version.py (1 hunks)
  • tests/fastapi/test_loggin_route.py (5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: Format code with Black and sort imports with isort (make format)
Pass linting with flake8 and formatting checks (isort --check-only, black --check)
Maintain type correctness with mypy (make lint runs mypy)

Files:

  • tests/fastapi/test_loggin_route.py
  • agave/version.py
  • agave/fastapi/middlewares/loggin_route.py

⚙️ CodeRabbit configuration file

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

`*...

Files:

  • tests/fastapi/test_loggin_route.py
  • agave/version.py
  • agave/fastapi/middlewares/loggin_route.py
agave/fastapi/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

agave/fastapi/**/*.py: Implement FastAPI-specific functionality under agave/fastapi/
In FastAPI modules, use async/await and mongoengine_plus.aio.AsyncDocument for MongoDB models

Files:

  • agave/fastapi/middlewares/loggin_route.py
agave/{fastapi,chalice}/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

agave/{fastapi,chalice}/**/*.py: Define REST resources as classes with model, validation, and CRUD methods; apply @app.resource('/path') to generate endpoints
Use Pydantic models for request/response validation with automatic error handling

Files:

  • agave/fastapi/middlewares/loggin_route.py
🧬 Code graph analysis (1)
agave/fastapi/middlewares/loggin_route.py (1)
agave/core/exc.py (1)
  • AgaveError (6-8)
🔇 Additional comments (3)
agave/version.py (1)

1-1: LGTM! Version bump is appropriate.

The version bump from 1.5.1 to 1.5.2 correctly reflects the addition of new error detail logging functionality in this release.

agave/fastapi/middlewares/loggin_route.py (1)

81-82: LGTM! Error detail logging correctly implemented.

The exception handler now properly captures both status code and error detail, providing more comprehensive logging for debugging.

tests/fastapi/test_loggin_route.py (1)

100-103: LGTM! Test assertions properly validate error detail logging.

The new assertions comprehensively verify that error details are correctly captured and logged for various exception types:

  • ValidationError with detailed field information
  • HTTPException messages (Not found, Bad request, Unauthorized)
  • Generic Exception messages (Internal server error)

This ensures the new get_error_detail function works correctly across all supported exception types.

Also applies to: 125-125, 286-286, 302-303, 319-320

@codecov
Copy link

codecov bot commented Oct 17, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (03ce8c7) to head (6de3399).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #179   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           19        19           
  Lines          710       711    +1     
  Branches        74        74           
=========================================
+ Hits           710       711    +1     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@gmorales96 gmorales96 requested a review from felipao-mx October 21, 2025 16:04
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
agave/fastapi/middlewares/loggin_route.py (1)

23-23: Use json.dumps for cleaner validation error logging.

Currently, str(exc.errors()) produces Python's repr-like output [{'loc': ..., 'msg': ...}] which is harder to read in logs. Since this string gets stored in log_data['response']['error'] and the entire structure is JSON-serialized at line 99, using json.dumps(exc.errors()) will produce properly formatted JSON.

Apply this diff:

-        return 422, str(exc.errors())
+        return 422, json.dumps(exc.errors())
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22ae8a1 and 6de3399.

📒 Files selected for processing (3)
  • agave/fastapi/middlewares/loggin_route.py (2 hunks)
  • agave/version.py (1 hunks)
  • tests/fastapi/test_loggin_route.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • agave/version.py
  • tests/fastapi/test_loggin_route.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: Format code with Black and sort imports with isort (make format)
Pass linting with flake8 and formatting checks (isort --check-only, black --check)
Maintain type correctness with mypy (make lint runs mypy)

Files:

  • agave/fastapi/middlewares/loggin_route.py

⚙️ CodeRabbit configuration file

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

`*...

Files:

  • agave/fastapi/middlewares/loggin_route.py
agave/fastapi/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

agave/fastapi/**/*.py: Implement FastAPI-specific functionality under agave/fastapi/
In FastAPI modules, use async/await and mongoengine_plus.aio.AsyncDocument for MongoDB models

Files:

  • agave/fastapi/middlewares/loggin_route.py
agave/{fastapi,chalice}/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

agave/{fastapi,chalice}/**/*.py: Define REST resources as classes with model, validation, and CRUD methods; apply @app.resource('/path') to generate endpoints
Use Pydantic models for request/response validation with automatic error handling

Files:

  • agave/fastapi/middlewares/loggin_route.py
🧬 Code graph analysis (1)
agave/fastapi/middlewares/loggin_route.py (2)
tests/utils.py (1)
  • status_code (32-33)
agave/core/exc.py (1)
  • AgaveError (6-8)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: pytest (3.10)
  • GitHub Check: pytest (3.13)
  • GitHub Check: pytest (3.11)
  • GitHub Check: pytest (3.12)
  • GitHub Check: coverage
  • GitHub Check: pytest (3.9)
🔇 Additional comments (2)
agave/fastapi/middlewares/loggin_route.py (2)

68-74: Excellent implementation addressing past feedback.

The changes correctly unpack both status code and error detail, and log them in the response. This successfully addresses felipao-mx's suggestion to unify the functions and return a tuple.


27-27: Verify that CuencaError from cuenca_validations.errors has a status_code attribute.

The code at line 27 accesses exc.status_code on CuencaError instances. While web searches confirmed that cuenca_validations.errors.CuencaError is the package's base exception class for validation-related errors, the search results did not explicitly confirm that this class exposes a status_code attribute. Please verify against the cuenca-validations package documentation or source code that this attribute exists before merging.

@felipao-mx felipao-mx merged commit e7aa7f5 into main Oct 21, 2025
12 checks passed
@felipao-mx felipao-mx deleted the feat/fastapi-loggin-route-error-detail branch October 21, 2025 19:58
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.

3 participants