You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BAH-5150 | Fix. Return 400 with message when dose calculation fails validation - #367
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.
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.
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.
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: 4
Check name
Status
Explanation
Title check
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description Check
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.
Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.
…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>
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.
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.
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.
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);
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/calculateDosefails 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,Chemotherapyin standard-config) callorg.openmrs.module.rulesengine.util.Validator.validate(...). When an observation is missing, it throws a plain checkedjava.lang.Exception("Please enter WEIGHT to calculate dose.").DoseCalculatorController.calculateDosedeclaredthrows Exception, so that exception went out as a 500.Fix
calculateDosenow returnsResponseEntity<Object>.WebUtils.wrapErrorResponse. Examples are a missing observation, an unknown rule, a drug missing from the dosage CSV, or malformeddosageRequestJSON (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.Dosebody) is unchanged.This follows the same pattern as
VisitDocumentControllerandFormDraftController.Response
Before:
HTTP 500After:
Tests
DoseCalculatorControllerTest(4 tests, all passing):Dosebody (updated for the new return type).dosageRequestJSON: asserts 400 and that the rules engine is not called.APIExceptionstill propagates (500).dosingRule: "ml/kg", returns the 400 shown above.Summary by CodeRabbit