I am subclassing Django's rest framework APIException class to create custom API exceptions. For example, one of my exceptions look like this:
class Unauthorized(APIException):
status_code = 401
default_detail = 'You have to login first.'
default_code = 'ERR_UNAUTHORIZED'
And I've written a custom exception handler to modify key names. This is the part in my exception handler that deals with these kinds of exceptions:
def custom_exception_handler(exc, context):
response.data['code'] = response.data['detail'].code
response.data['message'] = response.data['detail']
print(response.data)
del response.data['detail']
return response
As a result, the output for my exceptions looks like this :
{
"code": "ERR_UNAUTHORIZED",
"message": "You have to login first."
}
What I need to do is that I want to add a new field to my exceptions so that my exception output becomes like the below example:
{
"code": "ERR_UNAUTHORIZED",
"message": "You have to login first.",
"extra" : "{ "description" : "extra info" }"
}
And in my views, I want to throw this exception like this :
raise Unauthorized(extra={ "description" : "extra info" })
I'm quite new to Django rest_framework and I've searched about this and also tried to add the "another field" to my custom exception class fields but that couldn't solve my problem. Are there any ways to do something like this?