I need to make my API responses consistent based on my custom api_respone:
def api_response(success, message, data=None, error=None,
status_code=status.HTTP_200_OK, email_verified=None, token=None):
response = {
'success': success,
'message': message,
}
if data:
response['data'] = data
if error:
response['error'] = error
if email_verified is not None:
response['email_verified'] = email_verified
if token is not None:
response['token'] = token
return Response(response, status=status_code)
I created an exception handler:
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
custom_response_data = {
'success': False,
'message': response.data.get('detail', 'An error occurred.'),
'status_code': response.status_code,
}
response.data = custom_response_data
else:
custom_response_data = {
'success': False,
'message': str(exc),
'status_code': status.HTTP_500_INTERNAL_SERVER_ERROR,
}
return api_response(
success=custom_response_data['success'],
message=custom_response_data['message'],
status_code=custom_response_data['status_code']
)
return response
and added it in the setting.py:
'EXCEPTION_HANDLER': 'backend.exceptions.custom_exception_handler',
But it didn’t work at all and as a a result, I now have some custom responses (Hard coded) and others (The exception or permission exceptions) are not, which is not good.
How do I properly solve my problem?
here is an example of a view code:
class PasswordUpdateView(APIView):
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
def post(self, request):
user = request.user
serializer = UserPasswordUpdateSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
serializer.update(user, serializer.validated_data)
return api_response(True, "Password updated successfully")
return api_response(False, "Password update failed", error=serializer.errors, status_code=status.HTTP_400_BAD_REQUEST)
In this case, if the jwt token is expired, the exception response returned is not formatted based on my custom api_response.
I hope I made my situation clear. Thanks in advance