Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 How to capture an error message
#1
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 int
I 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
Quote
#2
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.
Quote
#3
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?
Quote
#4
try:
    print('2'+2)
except TypeError as err:
    errormessage = err

print errormessage
Output:
TypeError('must be str, not int',)
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.
Quote
#5
(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')
Output:
λ cat output.log 2020-02-15 15:42:45.104 | ERROR | __main__:add:8 - msg Traceback (most recent call last): File "add_guru.py", line 11, in <module> add(5, '50') -> <function add at 0x033308A0> > File "add_guru.py", line 6, in add return(x + y) | -> '50' -> 5 TypeError: unsupported operand type(s) for +: 'int' and 'str'
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')
Output:
λ cat file_1.log 2020-02-15 15:59:35.736 | ERROR | __main__:<module>:12 - An error has been caught in function '<module>', process 'MainProcess' (13600), thread 'MainThread' (10060): Traceback (most recent call last): > File "catch_guru.py", line 12, in <module> add(5, '99') -> <function add at 0x0320AF60> File "catch_guru.py", line 9, in add return(x + y) | -> '99' -> 5 TypeError: unsupported operand type(s) for +: 'int' and 'str'
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to send an error message Ewilliam51 1 106 Feb-15-2020, 08:41 AM
Last Post: ndc85430
  Error Message Coming Up When Running Code eddywinch82 0 251 Feb-10-2020, 11:48 PM
Last Post: eddywinch82
  Error message when trying to install Matplotlib in Python3.8 Transitionyte 5 482 Jan-22-2020, 11:52 PM
Last Post: Transitionyte
  capture next block of text after finding error in file kdefilip2 6 250 Nov-27-2019, 07:36 PM
Last Post: buran
  How to get valid error message while invoking REST API through Python gollupraveen 0 157 Oct-04-2019, 07:15 PM
Last Post: gollupraveen
  Project, Reading Data from a spreadsheet. Error message!! Shafla 1 269 Sep-27-2019, 10:44 AM
Last Post: buran
  object is not subscriptable... Error Message? Shafla 3 859 Sep-25-2019, 12:27 AM
Last Post: buran
  Openpyxl error message. Help! Shafla 6 349 Sep-24-2019, 07:25 PM
Last Post: Shafla
  clueless about the error message findbikash 2 293 Sep-19-2019, 01:10 PM
Last Post: findbikash
  My class has name error message 357mag 3 251 Sep-04-2019, 03:29 PM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)