Skip to content

Commit 744fb6c

Browse files
committed
Improve stock ID error message formatting
Add custom StockIDNotFoundError exception that properly handles newlines in error messages when a stock ID is not found in the database. This makes the error more readable and provides clear instructions for users on how to update their stock codes database.
1 parent 2098c2a commit 744fb6c

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

twstock/stock.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@
4242
)
4343

4444

45+
class StockIDNotFoundError(KeyError):
46+
"""Exception raised when a stock ID is not found in the database."""
47+
48+
def __str__(self):
49+
return super().__str__().replace("\\n", "\n")
50+
51+
4552
class BaseFetcher(object):
4653
def fetch(self, year, month, sid, retry):
4754
pass
@@ -155,6 +162,15 @@ def purify(self, original_data):
155162

156163
class Stock(analytics.Analytics):
157164
def __init__(self, sid: str, initial_fetch: bool = True):
165+
if sid not in codes:
166+
raise StockIDNotFoundError(
167+
f'Stock ID "{sid}" not found in database.\n'
168+
"Either you misspelled it or it is not in the database.\n"
169+
"If you believe your stock ID is correct, please update stock codes database using:\n"
170+
" - CLI: twstock -U\n"
171+
' - Python: python -c "import twstock; twstock.__update_codes()"'
172+
)
173+
158174
self.sid = sid
159175
self.fetcher = (
160176
TWSEFetcher() if codes[sid].data_source == "twse" else TPEXFetcher()

0 commit comments

Comments
 (0)