You could create a custom exception class as below, and it would raise APIException with a custom message
and custom status_code
from rest_framework.serializers import ValidationError
from rest_framework import status
class CustomAPIException(ValidationError):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'
def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code
and in your views
,
from rest_framework import status
try:
obj = self.get_object()
except:
raise CustomAPIException("This object does not exist", status_code=status.HTTP_404_NOT_FOUND)
The response will be like this
{"detail": "This object does not exist"}
NOTE
the detail
parameter of CustomAPIException
class takes str
,list
and dict
objects. If you provide a dict
object, then it will return that dict as exception response
UPDATE
As @pratibha mentioned, it's not possible to produce desired output if we use this exception class in Serializer's validate()
or validate_xxfieldName()
methods.
Why this behaviour ?
I wrote a similar answer in SO, here Django REST Framework ValidationError always returns 400
How to obtain desired output within the serializer's validate()
method?
Inherit CustomAPIException
from rest_framework.exceptions.APIException
instead of from rest_framework.serializers.ValidationError
ie,
from rest_framework.exceptions import APIException
class CustomAPIException(APIException):
# .... code