How to capture an error message - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to capture an error message (/thread-24436.html) |
How to capture an error message - TheHacker707 - Feb-14-2020 Hello, I need a way to capture an error message in a variable. For example: >>> print('2'+2) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> print('2'+2) TypeError: must be str, not intI want to be able to capture this Traceback error message in a variable, maybe using a try: except: block. So what I want to know is: is there a way to get this error in a variable? -707 RE: How to capture an error message - Larz60+ - Feb-14-2020 try/except is the proper way to go, example: import sys try: print('2'+2) except TypeError: print(f"Caught a TypeError exception") sys.exit(0)I added an exit, but you can remove it if you want to analyse the code further. However, never leave errors in code you plan to release. RE: How to capture an error message - TheHacker707 - Feb-15-2020 OK, but what I want to do is capture the error message in a variable, so that I can save it to a log or something. Is there a way to do that? RE: How to capture an error message - ibreeden - Feb-15-2020 try: print('2'+2) except TypeError as err: errormessage = err print errormessage This behavior is described in 8. Errors and Exceptions. You can query more information from the Exception object. On the python commandline you can do help(Exception) to get more information about the Exception object.Sorry I forgot to mention the need to import sys .
RE: How to capture an error message - snippsat - Feb-15-2020 (Feb-15-2020, 02:54 AM)TheHacker707 Wrote: so that I can save it to a log or something. Is there a way to do that?Can do it with logging module,look at this post. In that post i use logging in standard library,you see i have to write boiler plate code and i import it with import my_log .There is a easier way if using eg Loguru. No boiler plate code,if i use same function as in post. from loguru import logger logger.add("output.log", backtrace=True, diagnose=True) def add(x, y): try: return(x + y) except Exception as error: logger.exception('msg') if __name__ == '__main__': add(5, '50') Loguru can also catch error even if not using try:except ,bye using a decorator.from loguru import logger logger.add("file_1.log", rotation="5 MB") @logger.catch def add(x, y): return(x + y) if __name__ == '__main__': add(5, '99')
|