Django-rest-framework: Create should give much more useful exceptions when TypeError occurs

Created on 15 Oct 2015  ·  3Comments  ·  Source: encode/django-rest-framework

This is the bane of my life. Line 845 in serializers.py needs to be changed to be a lot more helpful when a TypeError does occur.

If you have custom .save() methods and something goes wrong then DRF only gives you the exception message, which might be as useful as "X is not iterable". Can DRF perhaps include the traceback of the original TypeError or do _anything_ a bit more useful than spit out a default message and swallow the original exception?

Most helpful comment

Hi there,
I would really like to re-open this issue. This is really the worst part about using DRF in any non-trivial application. Here's the exception I'm getting:

TypeError: Got a `TypeError` when calling `Document.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Document.objects.create()`. You may need to make the field read-only, or override the DocumentSerializer.create() method to handle this correctly.
Original exception text was: 'SafeText' object is not callable.

I get you're trying to be helpful by displaying that text, but really you are swallowing the entire exception which makes it a lot harder to debug and throwing away most of the actually useful information. Please please consider my MR.

All 3 comments

I'd be happy to consider pull requests, but otherwise not obv what we should do differently here. We include the original exception text, but add a bit of extra context to explain why its being raised. No idea if we can (or would want to) preserve the original traceback.

I've made a PR, I think you should display the original traceback in the message. To be honest I think you should not catch the exception at all, but I guess the modified message might be helpful to new users. However it is swallowing important error information for no real reason, which should be changed.

Hi there,
I would really like to re-open this issue. This is really the worst part about using DRF in any non-trivial application. Here's the exception I'm getting:

TypeError: Got a `TypeError` when calling `Document.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Document.objects.create()`. You may need to make the field read-only, or override the DocumentSerializer.create() method to handle this correctly.
Original exception text was: 'SafeText' object is not callable.

I get you're trying to be helpful by displaying that text, but really you are swallowing the entire exception which makes it a lot harder to debug and throwing away most of the actually useful information. Please please consider my MR.

Was this page helpful?
0 / 5 - 0 ratings