How to show error again after script abort #11119
Replies: 6 comments 10 replies
-
Not sure it is smarter ... but what I do in the exception block is write the resultant error to a errors.txt which is stored in flash. Then you can re-visit that file on the next boot. |
Beta Was this translation helpful? Give feedback.
-
Try this: import io
import sys
def bad_func():
return 1 / 0
def good_func():
try:
return 1 / 0
except ZeroDivisionError as e:
print('-'*50)
print(f'good_func:{type(e)}')
print(f'good_func:{__name__}')
output = io.StringIO()
sys.print_exception(e, output)
print(output.getvalue())
print('-'*50)
return None
try:
good_func()
bad_func()
except Exception as e:
print('='*50)
print(f'Outer:{type(e)}')
print(f'Outer:{__name__}')
output = io.StringIO()
sys.print_exception(e, output)
print(output.getvalue())
print('='*50) |
Beta Was this translation helpful? Give feedback.
-
output = io.StringIO() # prepare
sys.print_exception(e, output) # print info into memory
s = output.getvalue() # retrieve the whole string
# do whatever you like to do with that string If you just want to log the raw data: try:
1 / 0
except Exception as e:
with open('logfile', 'a') as fh:
sys.print_exception(e, fh) |
Beta Was this translation helpful? Give feedback.
-
Thank you all for your support: This one seems to work for me: try:
main()
except Exception as e:
t=utime.localtime()
print("Exception")
errStr="\n===== Exception at "+str(t[3])+":"+str(t[4])+" "+str(t[2])+"."+str(t[1])+"."+str(t[0])+" =====\n"
with open('errors.txt', 'a') as outfile:
outfile.write(errStr)
sys.print_exception(e, outfile)
outfile.close()
print("errors.txt written successfully")
sys.exit() |
Beta Was this translation helpful? Give feedback.
-
By the way, I asked chatGPT (in German, translated by Deepl):
import sys
# diese Methode wird aufgerufen, sobald eine REPL-Verbindung hergestellt wird
def on_repl():
# prüfen, ob eine Exception aufgetreten ist
if sys.exc_info()[0] is not None:
# die letzte Exception ausgeben
sys.print_exception(*sys.exc_info())
# diese Methode registriert die "on_repl"-Methode als Callback
def register_on_repl_callback():
import builtins
if hasattr(builtins, "__REPL__"):
builtins.__REPL__.register_repl_callback(on_repl)
# Callback-Registrierung aufrufen
register_on_repl_callback()
I didn't try it because I didn't understand it. |
Beta Was this translation helpful? Give feedback.
-
Where do the German comments come from?
import sys
import time
import uasyncio as asyncio
from random import choice
from uasyncio import TimeoutError
ISO_FMT = "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}"
def random_exception():
exceptions = (
ValueError("You can't do this!"),
TypeError("I don't understand your operation."),
RuntimeError("Something which happens during runtime"),
TimeoutError("Timeout"),
KeyError("Key does not exist"),
IndexError("Index does not exist.")
)
raise choice(exceptions)
async def worker():
return 1 / 0
async def async_exception():
await asyncio.create_task(worker())
def main():
if choice([True, False]):
print("Sync code")
random_exception()
else:
print("Async code")
asyncio.run(async_exception())
def exc_catcher(debug=False):
if not debug:
return main()
try:
main()
except Exception as e:
with open("error.txt", "a") as fd:
fd.write(ISO_FMT.format(*time.localtime()[:6]))
fd.write("\n")
sys.print_exception(e, fd)
fd.write("\n")
if __name__ == "__main__":
exc_catcher(debug=True)
print("Program End") |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I have a larger micropython script running on an ESP32. After some hours or days it seems, the script cancels because of an exception. I can login via web repl and get a working prompt. A new import of the script has no effect, so I'm sure, a reboot es not the cause of the problem.
After a reboot, an import of the script always runs the script, which doesn't work after an exception.
Is there a way to repeat the last error output of a script?
Currently I have no idea which module of my script throws the exception.
I can put a serial data logger (which I currently doesn't have) on serial interface of the ESP-module to get the root cause. But es there a smarter approach?
Beta Was this translation helpful? Give feedback.
All reactions