Skip to content

BAH-5150 | Fix. Return 400 with message when dose calculation fails validation - #367

Open
mahrukh-anwari wants to merge 2 commits into
masterfrom
feature/BAH-5150
Open

mahrukh-anwari wants to merge 2 commits into
masterfrom
feature/BAH-5150

Conversation

@mahrukh-anwari

@mahrukh-anwari mahrukh-anwari commented Nov 23, 2026 •

Copy link
Copy Markdown

Problem

When a medication with a dosing rule is added (Clinical → Medications, e.g. "Activated charcoal (Powder)") for a patient with no WEIGHT observation, GET /openmrs/ws/rest/v1/bahmnicore/calculateDose fails with HTTP 500. The UI then shows the generic "There was an unexpected issue on the server" banner.

Root cause

The dosing rules (MlPerKgDosageRule, MicrogramPerKgDosageRule, Chemotherapy in standard-config) call org.openmrs.module.rulesengine.util.Validator.validate(...). When an observation is missing, it throws a plain checked java.lang.Exception("Please enter WEIGHT to calculate dose."). DoseCalculatorController.calculateDose declared throws Exception, so that exception went out as a 500.

Fix

  • calculateDose now returns ResponseEntity<Object>.
  • Checked exceptions from the rules engine are returned as HTTP 400, with the engine's message in the standard OpenMRS error body built by WebUtils.wrapErrorResponse. Examples are a missing observation, an unknown rule, a drug missing from the dosage CSV, or malformed dosageRequest JSON (IOException).
  • RuntimeExceptions, e.g. APIException "Concept [X] is not configured in rules.", are rethrown and still give 500. Server or configuration faults are therefore not reported as user errors.
  • The success response (200 with the Dose body) is unchanged.

This follows the same pattern as VisitDocumentController and FormDraftController.

Response

Before: HTTP 500

After:

HTTP 400
{"error":{"message":"Please enter WEIGHT to calculate dose."}}

Tests

  • DoseCalculatorControllerTest (4 tests, all passing):
    • Success: asserts 200 and the Dose body (updated for the new return type).
    • Rule validation failure: asserts 400 and the exact message.
    • Malformed dosageRequest JSON: asserts 400 and that the rules engine is not called.
    • APIException still propagates (500).
  • Manually verified on a local bahmni-standard docker setup with the rebuilt omod. A patient without a weight observation, using dosingRule: "ml/kg", returns the 400 shown above.
Screenshot 2026-11-23 at 12 16 51

Summary by CodeRabbit

  • Bug Fixes
    • Dose calculation requests now return an explicit success response when calculations complete.
    • Invalid requests and general calculation errors return HTTP 400 responses with an error message.
    • API exceptions continue to propagate.

@CLAassistant

CLAassistant commented Nov 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d7899504-4661-4200-acb2-8e98b5c64fbe
Commits

Reviewing files that changed from the base of the PR and between 7dbcb78 and 5fc0b15.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The dose calculator controller now returns ResponseEntity<Object>. Successful calculations return HTTP 200; handled exceptions return HTTP 400, while runtime exceptions propagate. Tests cover these responses and malformed JSON.

Changes: Dose calculation response handling

Layer / File(s) Summary
Controller responses and validation
bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/DoseCalculatorController.java, bahmnicore-omod/src/test/java/org/bahmni/module/bahmnicore/web/v1_0/controller/DoseCalculatorControllerTest.java
The controller returns the calculated dose with HTTP 200 and wraps other exceptions in HTTP 400 responses. Runtime exceptions propagate. Tests check successful responses, general exceptions, malformed JSON, and APIException propagation.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: alagesann, sidtharthanan

Merge Risk: Minimal · previous review 7dbcb

Dose calculation failures such as a missing weight now return a clear HTTP 400 message instead of a server error. The change is small and covered by tests, and no merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: dose calculation validation failures now return HTTP 400 with a message instead of a 500 error. It matches the controller change in DoseCalculatorController (checked e…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: dose calculation validation failures now return HTTP 400 with a message instead of a 500 error. It matches the controller change in DoseCalculatorController (checked exceptions wrapped into a 400 response) and the added tests. The BAH-5150 ticket prefix and the 'Fix.' label are conventions, not noise that hides the change. The title is 78 characters, slightly long but still one readable sentence.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff0a1f78-d1d3-48f5-a63e-1f5a0acb6367
Commits

Reviewing files that changed from the base of the PR and between a96c8b8 and 7dbcb78.

Files selected for processing: 2

  • bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/DoseCalculatorController.java
  • bahmnicore-omod/src/test/java/org/bahmni/module/bahmnicore/web/v1_0/controller/DoseCalculatorControllerTest.java

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

mahrukh-anwari and others added 2 commits November 23, 2026 13:15
…alidation

The rules engine signals user-correctable problems (e.g. missing weight
or height observation) with plain checked exceptions, which the
calculateDose endpoint let propagate as an HTTP 500.

Catch checked exceptions in DoseCalculatorController and return 400 with
the rule's message in the standard {"error": {"message": ...}} body.
Runtime exceptions (e.g. rules misconfiguration) still propagate as 500.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@sahupadma sahupadma left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review for BAH-5150

Good fix overall — correctly distinguishes checked validation exceptions (→ 400) from RuntimeException/APIException config faults (→ still 500), and follows the existing ResponseEntity + WebUtils.wrapErrorResponse pattern already used in VisitDocumentController. Test coverage for the four scenarios (success, validation failure, malformed JSON, runtime exception propagation) is solid.

Found 0 blocking issues, 1 suggestion, and 2 nits.

Acceptance Criteria: Backend 500→400 behavior fully covered and verified.

throw e;
} catch (Exception e) {
log.warn("Unable to calculate dose: " + e.getMessage());
return new ResponseEntity<>(WebUtils.wrapErrorResponse(null, e.getMessage()), HttpStatus.BAD_REQUEST);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: e.getMessage() can be null for some exception types. WebUtils.wrapErrorResponse only adds the "message" key when reason is non-null/non-empty, so a null message here would produce an unhelpful {"error":{}} 400 body with no explanation for the client.

Consider: WebUtils.wrapErrorResponse(null, e.getMessage() != null ? e.getMessage() : "Dose calculation failed validation")

question: Also worth a thought — any checked exception's message from the rules engine is returned verbatim in the response body. Matches the existing VisitDocumentController precedent, so not a new pattern, but if the rules engine is later extended with exceptions carrying internal details (paths, wrapped messages), those would leak to the API response.

} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
log.warn("Unable to calculate dose: " + e.getMessage());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: log.warn only logs the message string, not the throwable e. Sibling controllers (VisitDocumentController, EmailCommunicationController) pass the exception object so the stack trace is preserved for debugging.

log.warn("Unable to calculate dose: " + e.getMessage(), e);

}

@Test
public void shouldReturnBadRequestWithValidationMessageWhenRuleValidationFails() throws Exception {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: Both failure tests use exceptions with a non-null message. Consider adding a case with new Exception() (null message) to cover the empty-error-body edge case noted above.

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