【问题标题】:Django rest_framework custom errror handlerDjango rest 框架自定义错误处理程序
【发布时间】:2020-12-08 11:40:22
【问题描述】:

我想像烧瓶自定义错误处理程序一样编写 django 自定义错误处理程序。 假设我有 100 个 api,每次都会得到相同的错误,让我们说

json.decoder.JSONDecodeError

示例代码

def post(self, request):
    if not request: return Response({"message": "Please enter credentials"})
    input_param = json.load(request)
    print(input_param)
    return "something"

如果 post 请求中没有传递参数,上述代码将返回 json.decoder.JSONDecodeError

在烧瓶中,这可以通过编写自定义错误处理程序来处理,例如


@app.errorhandler(json.decoder.JSONDecodeError)
def handle_marshmallow_validaton_errors(err):
    
    return jsonify({"error": "Bad request"}), 400

在 django 中有什么方法可以编写自定义错误处理程序

提前致谢

【问题讨论】:

    标签: python django error-handling


    【解决方案1】:

    我认为您可以使用 DRF 自定义异常处理程序 https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling。 您可以使用它来检查生成异常并返回正确的响应。

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2018-04-29
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多