Reputation:
While using django and django rest framework and strictly using the frame work code.
Example,
using a router connected to a view set to a serializer into a model.
What I mean is no custom code, other than what is required to feed into the django rest frameworks code, do we not need exceptions?
I ask because in all the code examples I have seen, I have yet to see a try catch block.
thank you
Upvotes: 3
Views: 997
Reputation: 2884
Generally, there will be some type of error thrown if the data is in the incorrect format or doesn't contain correct values such as a wrong data type or invalid primary key on some request. The Django REST Framework serializers take care of these kinds of errors by raising ValidationError
s and keeping track of errors in serializer.Serializer._errors
. The DRF framework presents these errors back to the user in a suitable format, for example:
{"detail": "Method 'DELETE' not allowed."}
when a user tried to send a HTTP DELETE request. More information on how DRF handles different exceptions can be found here.
As for code that you write yourself within views, serializers, models etc. that is up to you to try/except and handle however you deem necessary. Often in a serializer, you might use raise ValidationError(yourError)
and in a view you might return Response(yourError, status=400)
.
Hope I've helped.
Upvotes: 1