Skip to content

Comments

added exception handling and raising error for failed emails#3531

Open
praffq wants to merge 4 commits intodevelopfrom
prafful/bug/adding-exception-to-handle-reset-password-mail
Open

added exception handling and raising error for failed emails#3531
praffq wants to merge 4 commits intodevelopfrom
prafful/bug/adding-exception-to-handle-reset-password-mail

Conversation

@praffq
Copy link
Contributor

@praffq praffq commented Feb 13, 2026

Proposed Changes

  • Raise error when reset password email fails

Associated Issue

Architecture changes

  • Remove this section if not used

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

  • Bug Fixes

    • Users now receive a clear 503 error response if password-reset email delivery fails, preventing silent failures.
  • Tests

    • Added test coverage to confirm password reset requests surface email delivery failures and return the appropriate error response.
  • Documentation

    • Minor docstring update noting password stripping behavior during change-password handling.

@praffq praffq requested a review from a team as a code owner February 13, 2026 10:11
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2026

📝 Walkthrough

Walkthrough

Moves email-sending error handling from the utility into the view: the email utility no longer swallows exceptions, the reset-password view now catches send failures and returns HTTP 503, and a test was added asserting 503 on email-send exceptions.

Changes

Cohort / File(s) Summary
Email utility
care/emr/utils/reset_password.py
Removed logger and internal try/except from send_password_reset_email; token generation and email construction now run unconditionally and exceptions propagate instead of being swallowed.
View-layer change
care/users/reset_password_views.py
Wrapped send_password_reset_email call in ResetPasswordRequestToken.post with try/except; on exception returns HTTP 503 with a user-facing error message.
Tests
care/emr/tests/test_reset_password_api.py
Added test_reset_password_request_email_failure which mocks send_password_reset_email to raise and asserts a 503 response; minor docstring clarification about leading whitespace in password test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding exception handling and raising errors for failed password reset emails, which aligns with the code modifications across three files.
Description check ✅ Passed The description covers the core change and links to the associated issue, though the 'Architecture changes' section wasn't removed as requested and the merge checklist items remain unchecked despite being requirements.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into develop

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

✨ 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 prafful/bug/adding-exception-to-handle-reset-password-mail

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
care/users/reset_password_views.py (1)

182-187: Add logging to observe email delivery failures; the current blind exception catch swallows valuable debugging information.

The send_password_reset_email() function can raise various exceptions—from template rendering errors (TemplateDoesNotExist, TemplateSyntaxError) to email backend failures—so catching Exception at least prevents the endpoint from crashing. However, this means you're silently discarding the actual error details, which makes troubleshooting email delivery issues later... well, let's just say it'll be interesting.

The static analysis tool (BLE001) rightfully flags this. Adding a logger call would preserve the exception context for debugging without changing the user-facing error response.

♻️ Suggested improvement
+import logging
+
+logger = logging.getLogger(__name__)
+
 # ... in the post method ...
             try:
                 send_password_reset_email(user, mail_type)
             except Exception:
                 error_message = "Failed to send password reset email. Please try again."
+                logger.exception("Failed to send password reset email for user %s", user.username)
                 response = ResetPasswordResponse(detail=error_message).model_dump()
                 return Response(response, status=status.HTTP_503_SERVICE_UNAVAILABLE)

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

Copy link
Contributor

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
care/users/reset_password_views.py (1)

149-188: ⚠️ Potential issue | 🟠 Major

Return a structured ResetPasswordResponse (and document 503) for the new failure path.

Right now the 503 returns a bare string and the schema doesn’t mention 503. That’s a quiet contract change for clients. Please keep the response shape consistent and update the schema.

Proposed fix
     responses={
+        503: ResetPasswordResponse,
     },
@@
-            except Exception:
-                return Response(
-                    "Failed to send password reset email. Please try again.",
-                    status=status.HTTP_503_SERVICE_UNAVAILABLE,
-                )
+            except Exception:
+                error_message = "Failed to send password reset email. Please try again."
+                response = ResetPasswordResponse(detail=error_message).model_dump()
+                return Response(
+                    response,
+                    status=status.HTTP_503_SERVICE_UNAVAILABLE,
+                )
🤖 Fix all issues with AI agents
In `@care/users/reset_password_views.py`:
- Around line 182-188: Replace the blanket except Exception around the
send_password_reset_email call with explicit except clauses for email-related
failures (e.g., django.core.mail.BadHeaderError, smtplib.SMTPException) and
network errors (OSError, TimeoutError); for each caught exception log the
exception details (using the module logger or existing logging facility) and
then return the same 503 Response so unrelated bugs still surface, keeping the
try/except only around send_password_reset_email in the reset password view.

Copy link
Contributor

@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: 1

🤖 Fix all issues with AI agents
In `@care/users/reset_password_views.py`:
- Around line 182-190: The except block that catches exceptions from
send_password_reset_email currently returns a raw dict response; change it to
construct and return a ResetPasswordResponse(detail="Failed to send password
reset email. Please try again.").model_dump() with
status=status.HTTP_503_SERVICE_UNAVAILABLE so it matches the other error
responses in this file (same pattern used at lines referencing
ResetPasswordResponse elsewhere) and is returned from the except handling around
send_password_reset_email.

@codecov
Copy link

codecov bot commented Feb 13, 2026

Codecov Report

❌ Patch coverage is 70.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.45%. Comparing base (0d866d3) to head (f44f1ae).

Files with missing lines Patch % Lines
care/emr/utils/reset_password.py 70.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #3531   +/-   ##
========================================
  Coverage    75.45%   75.45%           
========================================
  Files          473      473           
  Lines        21977    21972    -5     
  Branches      2293     2293           
========================================
- Hits         16582    16579    -3     
+ Misses        4877     4875    -2     
  Partials       518      518           

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

1 participant