From f88728789bd61c5fb8db0436a3023a9e512f73e6 Mon Sep 17 00:00:00 2001 From: Maks Snegov Date: Sun, 22 Dec 2024 12:37:11 -0800 Subject: [PATCH] Handle exceptions when retrieving account balances --- src/gnucash_web/__init__.py | 1 + src/gnucash_web/templates/account.j2 | 4 ++-- src/gnucash_web/utils/jinja.py | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/gnucash_web/__init__.py b/src/gnucash_web/__init__.py index 3e3995c..3c044d2 100644 --- a/src/gnucash_web/__init__.py +++ b/src/gnucash_web/__init__.py @@ -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: diff --git a/src/gnucash_web/templates/account.j2 b/src/gnucash_web/templates/account.j2 index 4a70529..bf776c7 100644 --- a/src/gnucash_web/templates/account.j2 +++ b/src/gnucash_web/templates/account.j2 @@ -28,7 +28,7 @@
Total - {{ account.get_balance() | money(account.commodity) }} + {{ account | safe_get_balance | money(account.commodity) }}
@@ -54,7 +54,7 @@ - {{ account.get_balance() | money(account.commodity) }} + {{ account | safe_get_balance | money(account.commodity) }} diff --git a/src/gnucash_web/utils/jinja.py b/src/gnucash_web/utils/jinja.py index 17b6bad..51384a1 100644 --- a/src/gnucash_web/utils/jinja.py +++ b/src/gnucash_web/utils/jinja.py @@ -1,4 +1,5 @@ """Utilities for templates.""" +import logging import re from urllib.parse import quote_plus from itertools import islice, accumulate @@ -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): @@ -59,6 +61,9 @@ def money(eval_ctx, amount, commodity): :returns: HTML snippet """ + if amount is None: + return Markup('Error') + if numbers.get_currency_symbol(commodity.mnemonic) != commodity.mnemonic: value = numbers.format_currency(amount, commodity.mnemonic) else: @@ -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