def mhacks_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
if not response:
return response
if isinstance(response.data, str):
response.data = {'detail': response}
elif isinstance(response.data, list):
response.data = {'detail': response.data[0]}
elif not response.data.get('detail', None):
if len(response.data) == 0:
response.data = {'detail': 'Unknown error'}
elif isinstance(response.data, list):
response.data = {'detail': response.data[0]}
elif isinstance(response.data, dict):
first_key = response.data.keys()[0]
detail_for_key = response.data[first_key]
if isinstance(detail_for_key, list):
detail_for_key = detail_for_key[0]
if first_key.lower() == 'non_field_errors':
response.data = {'detail': "{}".format(detail_for_key)}
else:
response.data = {'detail': "{}: {}".format(first_key.title(), detail_for_key)}
else:
response.data = {'detail': 'Unknown error'}
return response
评论列表
文章目录