Reputation: 41
I am building a rest api in django, I am using postman to test my apis, Everything is great though I want if any error occurs in my django app so django send me a json error rather than a html page. Is there a way to do that.
Upvotes: 4
Views: 2187
Reputation: 20110
One of the ways is to extend django's JsonResponse class and use it while you catch any Django exception.
from django.http import JsonResponse
class HttpResponseInternalServerError(JsonResponse):
def __init__(self, message):
super().__init__({'message' : message}, status=503)
Upvotes: 0
Reputation: 1217
What you want is implementing your own Exception handler : https://www.django-rest-framework.org/api-guide/exceptions/
This works for any type of exceptions, and in the format you want.
Note that some exceptions are already nicely handled, like for instance with serializers and generic API, where responses are sent as json. An example can be missing required fields on a serializers or validation error, a bad permission, etc.
You can replace 400 and 500 handlers too to fill your purposes.
Upvotes: 2