Skip to content

Commit

Permalink
Improve error messages (#533)
Browse files Browse the repository at this point in the history
  • Loading branch information
vmartinv authored Jun 9, 2024
1 parent 83d5ff3 commit 49872ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
11 changes: 9 additions & 2 deletions cgt_calc/currency_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,15 @@ def _query_hmrc_api(self, date: datetime.date) -> None:
"https://www.trade-tariff.service.gov.uk/api/v2/"
f"exchange_rates/files/monthly_xml_{month_str}.xml"
)

response = self.session.get(url, timeout=10)
try:
response = self.session.get(url, timeout=10)
except Exception as err:
msg = f"Error while fetching HMRC exchange rates for the month {month_str} "
msg += f"from the following url: {url}.\n"
msg += "Either try again or if you're sure about the rates you can "
msg += f"add them manually in {self.exchange_rates_file}.\n"
msg += f"The error was: {err}\n"
raise ParsingError(url, msg) from err

if not response.ok:
raise ParsingError(
Expand Down
11 changes: 10 additions & 1 deletion cgt_calc/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ def convert_to_hmrc_transactions(
portfolio: dict[str, Decimal] = {}
acquisition_list: HmrcTransactionLog = {}
disposal_list: HmrcTransactionLog = {}
balance_history: list[Decimal] = []

for i, transaction in enumerate(transactions):
new_balance = balance[(transaction.broker, transaction.currency)]
Expand Down Expand Up @@ -257,11 +258,19 @@ def convert_to_hmrc_transactions(
raise InvalidTransactionError(
transaction, f"Action not processed({transaction.action})"
)
balance_history.append(new_balance)
if self.balance_check and new_balance < 0:
msg = f"Reached a negative balance({new_balance})"
msg += f" for broker {transaction.broker} ({transaction.currency})"
msg += " after processing the following transactions:\n"
msg += "\n".join(map(str, transactions[: i + 1]))
msg += "\n".join(
[
f"{trx}\nBalance after transaction={balance_after}"
for trx, balance_after in zip(
transactions[: i + 1], balance_history
)
]
)
raise CalculationError(msg)
balance[(transaction.broker, transaction.currency)] = new_balance
print("First pass completed")
Expand Down

0 comments on commit 49872ba

Please sign in to comment.