Skip to content

Commit

Permalink
Handle exceptions when retrieving account balances
Browse files Browse the repository at this point in the history
  • Loading branch information
snegov committed Dec 22, 2024
1 parent 0b1769c commit f887287
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/gnucash_web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def create_app(test_config=None):
app.jinja_env.filters['full_account_names'] = jinja_utils.full_account_names
app.jinja_env.filters['contrasplits'] = jinja_utils.contra_splits
app.jinja_env.filters['nth'] = jinja_utils.nth
app.jinja_env.filters['safe_get_balance'] = jinja_utils.safe_get_balance
app.jinja_env.globals['is_authenticated'] = auth.is_authenticated

with (Path(__file__).parent / 'version.txt').open() as version:
Expand Down
4 changes: 2 additions & 2 deletions src/gnucash_web/templates/account.j2
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<div class="list-group-item">
<b>Total</b>
<span class="float-end">
{{ account.get_balance() | money(account.commodity) }}
{{ account | safe_get_balance | money(account.commodity) }}
</span>
</div>
</div>
Expand All @@ -54,7 +54,7 @@
</a>

<span class="float-end">
{{ account.get_balance() | money(account.commodity) }}
{{ account | safe_get_balance | money(account.commodity) }}
</span>
</div>

Expand Down
14 changes: 14 additions & 0 deletions src/gnucash_web/utils/jinja.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Utilities for templates."""
import logging
import re
from urllib.parse import quote_plus
from itertools import islice, accumulate
Expand All @@ -8,6 +9,7 @@
from babel import numbers
from markupsafe import Markup, escape
from jinja2 import Environment, BaseLoader, pass_eval_context
from piecash import GnucashException


def safe_display_string(string):
Expand Down Expand Up @@ -59,6 +61,9 @@ def money(eval_ctx, amount, commodity):
:returns: HTML snippet
"""
if amount is None:
return Markup('<span class="text-danger">Error</span>')

if numbers.get_currency_symbol(commodity.mnemonic) != commodity.mnemonic:
value = numbers.format_currency(amount, commodity.mnemonic)
else:
Expand Down Expand Up @@ -132,3 +137,12 @@ def contra_splits(split):
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)


def safe_get_balance(account):
"""Get balance of account, but catch piecash exceptions."""
try:
return account.get_balance()
except GnucashException as e:
logging.warning(f"Failed to retrieve balance for account {account}: {e}")
return None

0 comments on commit f887287

Please sign in to comment.