【问题标题】:Django - Returning full exception trace to front-end on a 400Django - 在 400 上将完整的异常跟踪返回到前端
【发布时间】:2021-12-19 13:42:57
【问题描述】:

因此,仅出于封闭测试版和内部测试的目的,我试图在我的 Django 服务器中返回带有 400 错误的异常。下面是我如何在 Django 代码中执行此操作的示例。我有一个合作伙伴在前端工作,他们说他们无法从 400 响应中得到错误。我以为它会像response.body['error']。如何以前端可以提取的方式发回带有完整错误跟踪的 400?

except Exception as e:
    return Response(dict(error=str(e),
                         user_message=error_message_generic),
                    status=status.HTTP_400_BAD_REQUEST)

【问题讨论】:

    标签: python python-3.x django


    【解决方案1】:

    最常见的做法是这样的:

    from django.http import JsonResponse, HttpResponseBadRequest
    
    return HttpResponseBadRequest(JsonResponse({
        "error": "Malformed request",
        # Any other fields you'd want
    }))
    

    查看更多官方docs

    如果您有兴趣专门返回后端异常的回溯,您可以这样:

    
    from django.http import JsonResponse, HttpResponseBadRequest
    import traceback
    
    ...
    except Exception as e:
        return HttpResponseBadRequest(JsonResponse({
            "error": "Malformed request",
            "traceback": traceback.format_exc()
        }))
    
    traceback.format_exc()
    

    但这并不是在所有情况下都做到这一点的最佳方式。如果您确定该异常与用户的输入有关,那么回溯对用户没有太大帮助。你最好使用 Serializer,它的验证会更好。如果您只是提供有关未知错误的信息,我建议您使用HttpResponseServerError 并将您的异常记录到任何地方,例如sentry

    【讨论】:

    • 有趣。是不是我什么都不打算退货?我不知道是我做错了什么,还是我的搭档没有看错回复。
    • @user8714896 添加了一些细节。现在适合你吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2021-07-13
    • 1970-01-01
    • 2018-09-06
    • 2011-05-15
    • 2015-04-13
    • 1970-01-01
    • 2011-08-30
    相关资源
    最近更新 更多