1

I need to retrieve the name of the object in which an error has occured. The error is catched in a try exception statement. The error type as returned by err_type, value, traceback = sys.exc_info() looks like this:

In [1]: err_type
Out[2]: mainsite.models.PurchaseOrder.DoesNotExist 

I need to retrieve 'PurchaseOrder' as a string. The idea is to get the parent object and then use parent.__name__.However if I write err_type.__bases__ the result is:

In [3]: err_type.__bases__
Out[4]: (django.core.exceptions.ObjectDoesNotExist,) 

I don't know what is happening here, the Exception type is not a child of PurchaseOrder, but somehow it knows that the problem was in that object. How can I retrive "PurchaseOrder" from the Exception?

I am doing this in Django, but it seems to be a general python topic.

5
  • Is the module containing your PurchaseOrder class also called PurchaseOrder.py? In mainsite.models.PurchaseOrder.DoesNotExist it looks more like it's fully qualifying the module that DoesNotExist is from and not the object that threw the error. Commented Jul 26, 2020 at 1:35
  • 1
    It looks more like DoesNotExist is a nested class inside PurchaseOrder, but I agree that this output definitely does not say anything about what object was responsible for the error. Commented Jul 26, 2020 at 1:43
  • @user2357112supportsMonica oooo that is a very good point. I hadn't considered that, but I think you're right about it being a nested class. Commented Jul 26, 2020 at 1:48
  • @xgord no, PurchaseOrder is in models module. It is a class itself, not a module, but inherits from Django models.Model. It has the Excetion through its parent class I guess. Commented Jul 26, 2020 at 15:19
  • @user2357112supportsMonica in case is a nested class, how can I retrieve PurchaseOrder from the exception? Commented Jul 26, 2020 at 15:36

1 Answer 1

1

Here's two approaches.

You can already obtain a string:

names = str(err_type).split('.')

Perhaps you'd like to pick out your favorite component.


Alternatively, you may find that

value.__mro__

reveals what you were looking for. It will show all parents in a multiple inheritance (mixin) situation.


It's worth point out that a single catch Exception: may be a poor fit for you here. Consider using a more fine grained approach:

    try:
        result = query()

    catch mainsite.models.PurchaseOrder.DoesNotExist:
        handle_missing_purchase_order()

    catch mainsite.models.Approval.DoesNotExist:
        handle_missing_approval()

    catch Exception as e:
        handle_unknown_error(e)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.