SLDem
SLDem

Reputation: 2182

How to get the message value of a nested exception in Python?

I have an exception that looks like this:

exc = ProtocolError('Connection Aborted', BadStatusLine('No status line received'))

how can I access the No status line received part?

Here's the example situation:

def some_function():
    raise ProtocolError('Connection Aborted', BadStatusLine('No status line received'))

def some_other_function():
    try:
        some_function()
    except Exception as exc:
        if exc.message:
            details = exc.message
        else:
            details = exc

In the code above I'm trying to check if the returned exception has a message and if so I'm supposed to write it into the database, however when I call the exc.message it returns an empty string, and when I call exc it returns:

bson.errors.InvalidDocument: cannot encode object: ProtocolError('Connection Aborted', BadStatusLine('No status linereceived',)), of type: <class 'urllib3.exceptions.ProtocolError'>

so I cant write it into the database since its a type Exception not string, what I need to do is to see if the returned Exception has another nested Exception in it and get it's message.

Upvotes: 0

Views: 252

Answers (1)

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2688

I wasn't able to find the exact optimal way to fetch the inner message or exception but for quick assistance i wrote a utility function which by using regular expressions will return you inner exceptions or messages complete code is following

from urllib3.exceptions import ProtocolError
from http.client import BadStatusLine
import re

def FetchInnerExceptions(exc):
    result = []
    messages = str(exc).split(',')
    for msg in messages:
        m = re.search('''(?<=')\s*[^']+?\s*(?=')''', msg)
        if m is not None or m != '':
            result.append(m.group().strip())
    return result

def some_function():
    raise ProtocolError('Connection Aborted', BadStatusLine('No status line received'))

def some_other_function():
    try:
        some_function()
    except Exception as exc:
        e = FetchInnerExceptions(exc)
        print(e) #dumps all array or use index e[1] for your required message

some_other_function()

Upvotes: 1

Related Questions