from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        errors = dict()
        message = response.data.get('detail')
        if not message:
            for field, value in response.data.items():
                errors[field] = {'code': value[0].code, 'message': value[0]}
            response.data = {'success': False, 'data': None, 'message': 'Validation Error', 'errors': errors}
            response = Response(response.data, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            response.data = {'success': False, 'data': None, 'message': message, 'errors': [message]}

    return response