Thanks for the link. I could definitely catch specific exceptions, but catching all exceptions is what I really need. I’m researching it a bit and think I found a way.
This seems to mostly be a Python question and not an Anvil question.
Python has a sys.__excepthook__ that should do the trick. I’ll try to implement it tomorrow morning.
The except Exception as e: will catch all exceptions and the f'Error:<br>\n{traceback.format_exc()} will include in the email the whole traceback the way you would see it in the console, including the type of the exception.
EDIT: here is my code that works. I threw in print(traceback.format_exc()) so the traceback would also be in the app logs.
import traceback
@anvil.server.background_task
def function_name():
try:
#code here
except Exception as e:
print(traceback.format_exc())
send_error_email(f"""Scheduled Task function_name encountered an error.
\n{traceback.format_exc()}""")
EDIT2: A BIG caveat here is that the scheduled tasks no longer show as failed in the app log with the code above. To ensure the app log has the exception raised you can add a line to raise an exception so it will show in the app log correctly. This also allows me to remove the print statement with the traceback. Here is my final code:
import traceback
@anvil.server.background_task
def function_name():
try:
#code here
except Exception as e:
send_error_email(f"""Scheduled Task function_name encountered an error.
\n{traceback.format_exc()}""")
raise Exception(traceback.format_exc())