stefan.stt
stefan.stt

Reputation: 2627

Python build-in exceptions - how to get exception fields

I have the following error message:

type object 'SomeClass' has no attribute 'some_class_field'

The exception is of type 'AtrributeError'.

Is there any way to change the error message to:

Provider class 'SomeClass' has no field 'some_class_field'

I guess those parameters are saved in the python exception class and I think there could be a solution of the following type:

try:
    # some code
except AtrributeError as ae:
    print("Provider class '{0}' has no field '{1}'").format(ae.type_object, ae.attribute))
    exit(1)

Upvotes: 0

Views: 816

Answers (1)

Dinesh undefined
Dinesh undefined

Reputation: 5546

simply You cant do that.

if you do like that again you will exception like this

    print("Provider class '{0}' has no field '{1}'").format(ae.type_object, ae.attribute)
AttributeError: 'exceptions.AttributeError' object has no attribute 'type_object'

from Jim Fasarakis Hilliard comment:

we can't access like that because ae has only message key. it doesn't have any other key for what you are trying to access. Don't define your own exceptions; get the exception message from ae.args[0] and extract the parts you need. Then print them out (using .format or whatever else you need). – Jim Fasarakis Hilliard

Upvotes: 1

Related Questions