Django Rest框架中的自定义错误不起作用

2024-10-02 06:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从Django异常返回JSON响应,我实现了以下函数

def custom_exception_handler(exc, context):
if isinstance(exc, Http404):
    logging.exception('Uncaught Exception', exc_info=exc)
    return Response(str(exc), status=status.HTTP_404_NOT_FOUND)

response = exception_handler(exc, context)


if response is None:
    logging.exception('Uncaught Exception', exc_info=exc)
    return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
    logging.exception(exc.__cause__, exc_info=exc)

return response

我已经在我的settings.py文件中添加了这些

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'views.custom_exception_handler'
}

但我仍然得到一个HTML文件,而不是JSON响应


Tags: infojsonreturnifresponseloggingstatuscustom

热门问题