0

In django the exception IntegrityError could be caused by a lot of reasons.

Some times this error means a unique conflict. Some other times this could be caused by some foreign key check.

Currently we can only know the root cause by convert the exception into text:

(1062, "Duplicate entry '79d3dd88917a11e98d42f000ac192cee-not_created' for key 'fs_cluster_id_dir_e8164dce_uniq'")

But this is very unfriendly for program to identify. Is there any way for code to identify the root cause of exception?

For example, if I know this is caused by a unique conflict, I can tell the client this is caused because some resouce already exist. If I know this is caused by foreign key not exist, I can tell the client this is caused by some parent resource not created.

So can any good way to identify the cause by code?

Kramer Li
  • 2,284
  • 5
  • 27
  • 55
  • How about this, https://stackoverflow.com/questions/11293380/django-catching-integrity-error-and-showing-a-customized-message-using-template? – JPG Jun 19 '19 at 03:35
  • That answer only tell me how to cache and convert into a text message. I want to know any wayt to identify the error type(unique conflict, foreign key not exist) by code – Kramer Li Jun 19 '19 at 03:44
  • didn't **`e.__cause__`** return that details? – JPG Jun 19 '19 at 03:46
  • See [this question](https://stackoverflow.com/questions/53550833/in-django-how-can-i-programmatically-check-that-an-integrityerror-is-related-to/53551130#53551130) – Selcuk Jun 19 '19 at 03:54

1 Answers1

0

Don't know about good.

Do you need to identify the exact cause in your code? If you have an alternative way of proceeding that you want to avoid using every time because of efficiency considerations, you might just code:

try:
   # the simple way
except IntegrityError as simplefail:
   try:
      # the complicated way
   except IntegrityError as complexfail:
      # log this utter failure and re-raise one or other of the caught errors
nigel222
  • 7,582
  • 1
  • 14
  • 22