Skip to content

Comments

fix: add err handling to db queries#2064

Open
im-adithya wants to merge 4 commits intomasterfrom
fix/add-err-handling
Open

fix: add err handling to db queries#2064
im-adithya wants to merge 4 commits intomasterfrom
fix/add-err-handling

Conversation

@im-adithya
Copy link
Member

@im-adithya im-adithya commented Feb 12, 2026

Fixes #2061

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling for balance and budget retrieval operations to prevent silent failures and ensure accurate calculations.
    • Improved error reporting across financial operations to provide clearer error messages when operations fail.
    • Added comprehensive error detection to prevent partial or incomplete results from being returned to users.

@im-adithya im-adithya requested a review from rolznz February 12, 2026 08:20
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 12, 2026

📝 Walkthrough

Walkthrough

The pull request adds comprehensive error handling to two database query functions—GetBudgetUsageSat and GetIsolatedBalance—by changing their return types to include error values. All call sites throughout the codebase are updated to capture and handle these errors, ensuring failures in budget usage and balance retrieval operations are properly logged and propagated rather than silently ignored.

Changes

Cohort / File(s) Summary
Database Query Functions
db/queries/get_budget_usage.go, db/queries/get_isolated_balance.go
Updated function signatures to return (uint64, error) and (int64, error) respectively. Added error checks on database operations; functions now return early with error on query failure instead of returning default values.
API Layer
api/api.go
Updated GetApp and ListApps methods to handle errors from GetBudgetUsageSat and GetIsolatedBalance. Budget usage and balance fields are now set only on successful retrieval; errors are logged and propagated to callers.
NIP47 Controllers
nip47/controllers/get_balance_controller.go, nip47/controllers/get_budget_controller.go
Added error handling for balance and budget retrieval calls. On error, logs with request_event_id, publishes NIP47-formatted error responses, and returns early instead of proceeding with successful payloads.
Transaction Services
transactions/transactions_service.go
Enhanced validateCanPay and checkBudgetUsage methods with error handling for GetIsolatedBalance and GetBudgetUsageSat calls. Returns error messages on retrieval failures instead of proceeding with incomplete data.
Test Files
db/queries/get_isolated_balance_test.go, transactions/keysend_test.go, transactions/self_payments_test.go
Updated test calls to capture and assert on returned errors. Test assertions now verify error-free execution before validating balance values, preventing silent failures in test scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit hops through errors deep,
No more silent failures to creep,
Each query checks before it flies,
With logs to shine, no more surprise! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding error handling to database queries across multiple files and API endpoints.
Linked Issues check ✅ Passed The PR adds comprehensive error handling to database queries (GetBudgetUsageSat, GetIsolatedBalance) and their call sites, directly addressing the objective in issue #2061.
Out of Scope Changes check ✅ Passed All changes are scoped to adding error handling for database queries; no unrelated modifications are present.

✏️ 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 fix/add-err-handling

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

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: 3

Caution

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

⚠️ Outside diff range comments (1)
nip47/controllers/get_balance_controller.go (1)

46-48: ⚠️ Potential issue | 🟠 Major

Pre-existing: potential nil dereference if GetBalances fails.

balance = balances.Lightning.TotalSpendable on Line 47 executes before the error check on Line 48. If GetBalances returns an error and a nil/zero-valued balances, this could panic. Not introduced by this PR, but worth fixing since you're already touching this function.

Proposed fix
 	} else {
 		balances, err := controller.lnClient.GetBalances(ctx, true)
-		balance = balances.Lightning.TotalSpendable
 		if err != nil {
 			logger.Logger.WithFields(logrus.Fields{
 				"request_event_id": requestEventId,
 			}).WithError(err).Error("Failed to fetch balance")
 			publishResponse(&models.Response{
 				ResultType: nip47Request.Method,
 				Error:      mapNip47Error(err),
 			}, nostr.Tags{})
 			return
 		}
+		balance = balances.Lightning.TotalSpendable
 	}
🤖 Fix all issues with AI agents
In `@api/api.go`:
- Around line 585-592: In ListApps, a failure from queries.GetIsolatedBalance
currently returns the error and aborts the whole listing; change this to match
GetApp's soft-fail behavior: if queries.GetIsolatedBalance(api.db, dbApp.ID)
returns an error, log it with
logger.Logger.WithError(err).WithFields(...).Error("Failed to get isolated app
balance") and do NOT return — instead set apiApp.Balance to a safe default
(e.g., zero or nil depending on the Balance type) and continue processing the
rest of apps so a single isolated balance DB hiccup doesn't fail the entire
ListApps result.

In `@transactions/transactions_service.go`:
- Around line 1057-1060: The error returned from GetIsolatedBalance is
discarded; update the error return in the block that calls
queries.GetIsolatedBalance(tx, appPermission.AppId) to wrap the original err
(e.g., using fmt.Errorf with %w) and include context such as the app id and a
short message—replace the current return errors.New(...) with something like
fmt.Errorf("failed to calculate isolated balance for app %s: %w",
appPermission.AppId, err) so the root cause is preserved when propagated from
functions like the transaction creator.
- Around line 1087-1090: The error returned from queries.GetBudgetUsageSat(tx,
&appPermission) is being discarded; change the return to include the original
err (e.g., use fmt.Errorf or errors.Wrap) so the root cause is preserved when
returning from the current function where GetBudgetUsageSat and appPermission
are used; ensure the returned message still describes the context (e.g., "failed
to calculate budget usage for app: %w", err).
🧹 Nitpick comments (2)
api/api.go (2)

428-433: Inconsistent error handling pattern within GetApp: BudgetUsage is always set (even on error), but Balance is conditionally set.

On error, budgetUsage defaults to 0 and is unconditionally assigned at line 462. This means a DB failure silently shows zero usage, potentially misleading the caller into thinking the full budget is available. Compare with the Balance handling at lines 472–479, which only sets the field on success.

Consider either returning an error or guarding assignment like you did for Balance:

Proposed fix
 	budgetUsage, err := queries.GetBudgetUsageSat(api.db, &paySpecificPermission)
 	if err != nil {
 		logger.Logger.WithError(err).WithFields(logrus.Fields{
 			"app_id": dbApp.ID,
 		}).Error("Failed to get budget usage for app")
+	} else {
+		response.BudgetUsage = budgetUsage
 	}

And remove the static assignment at line 462:

-		BudgetUsage:        budgetUsage,

601-608: Same hard-fail concern as the isolated balance query above.

Budget usage query failure for a single app also aborts the entire ListApps response. This is consistent with the pattern at line 590, but both differ from the soft-fail approach in GetApp. Consider aligning the error handling strategy across both methods.

}, nostr.Tags{})
return
}
balance = balances.Lightning.TotalSpendable
Copy link
Member Author

Choose a reason for hiding this comment

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

Coderabbit saves the day, yet again 😁

Copy link
Contributor

Choose a reason for hiding this comment

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

Could you have a look and see if we can add any missing tests to make sure we do not rely on Coderabbit

@im-adithya im-adithya requested a review from rolznz February 12, 2026 09:40
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.

Add error handling to DB queries

2 participants