Python Callback Exception Handling
When using Python callback functions, because they run in a separate thread, if an error occurs during the execution, the error message will not be automatically thrown back, which may cause obstacles in debugging.
To resolve this, you can add the following decorator to the callback function. When an error occurs in the code, the error will be displayed in the console as usual:
import os
import sys
import traceback
import functools
def handle_exceptions(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exp:
# Extract the full traceback
tb_lines = traceback.format_exc().splitlines()
# Find the index of the line related to the original function
func_line_index = next((i for i, line in enumerate(tb_lines) if func.__name__ in line), -1)
# Highlight the specific part in the traceback where the exception occurred
relevant_tb = "\n".join(tb_lines[func_line_index:]) # Include traceback from the function name
error_text = f"{func.__name__} exception: {exp}\nTraceback (most recent call last):\n{relevant_tb}"
print(error_text, file=sys.stderr)
# If you want to terminate the program completely, add the following line (P.S. Don't use with Jupyter)
# os._exit(-1)
return wrapper
def on_event(code, content):
print("===event=====")
print(code)
print(content)
print("========")
@handle_exceptions
def on_order(code, content):
print("==Order==")
print(code)
print(content)
print("========")
# Add some code that would cause exceptions
test = {}
print(test["key"]) # This will throw exception
In the above sample code, we deliberately put a line print(test["key"])
in on_order. Because "key"
is not in the dictionary test
, an error will occur.
At this time, because we have added the @handle_exceptions
decorator, after receiving a new order callback message, the console will print out:
on_order exception: 'key'
Traceback (most recent call last):
File "xxx.py", line 47, in on_order
print(test["key"])
~~~~^^^^^^^
KeyError: 'key'