In Django REST Framework, when you query a database model and it does not exist an exception will be raised as ModelName.DoesNotExist
.
This exception will change according to the model name.
For example:
Car
model will raise Car.DoesNotExist
Plane
model will raise Plane.DoesNotExist
This causes trouble, since you can not catch the exception at one common place, because you do not know the parent class of the Exception.
You have to catch a different exception every time you query a different model, for example:
try:
return Car.objects.get(pk=1)
except Car.DoesNotExist:
raise Http404
Why was this feature designed like this?
Is it possible to capture a common exception?
I want to return a HTTP 400 response from my django view function if the request GET data is invalid and cannot be parsed. Return a HttpResponseBadRequest : docs.djangoproject.com/en/dev/ref/request-response/… You can create an Exception subclass like Http404 to have your own Http400 exception.
The easiest way to change the error style through all the view in your application is to always use serializer. is_valid(raise_exception=True) , and then implement a custom exception handler that defines how the error response is created.
You can use ObjectDoesNotExist
:
from django.core.exceptions import ObjectDoesNotExist
try:
return Car.objects.get(pk=1)
except ObjectDoesNotExist:
raise Http404
ObjectDoesNotExist
will catch DoesNotExist
exceptions for all models.
Django also provides get_object_or_404()
shortcut so you dont need to raise Http404 explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With