【问题标题】:Jsonify Exception errorsJsonify 异常错误
【发布时间】:2020-08-21 06:04:32
【问题描述】:

在尝试处理 Flask Rest API 中的错误时,我想返回错误消息和状态代码的 json 版本。我尝试了以下

@app.route("/model/test/",methods=["GET"])
def show():
    try:
        num=request.args['num']
        return jsonify({'result':num,'response':'200 OK'})
    except Exception as e:


        return jsonify({'error':e})

当我使用http://localhost:5000/model/test/?ummm=30 访问GET 方法时。我有一个错误异常不能被 jsonified 关于如何按照我的意愿提供错误输出的任何帮助?

【问题讨论】:

    标签: python-3.x flask error-handling flask-restful rest


    【解决方案1】:

    json 不支持多种格式。 Python 解码/编码规则可以在here 找到。我建议从异常中提取文本并添加状态码,可能是"error" : "Message: {}, status 400 Bad request".format(e)?或者您可以单独添加status-code

    【讨论】:

      【解决方案2】:

      你可以,例如:

      def my_function():
          if request.method == 'PUT':
              try:
                  a_test_function(request)
                  return {
                      'message': 'Request is a good request.',
                      'status': 200,
                  }, 200
              except ValueError as error:
                  return {
                      'message': "Bad request!",
                      'status': 400,
                      'Error': str(error),
                  }, 400
              except:
                  return {
                      'message': "Bad request!",
                      'status': 400,
                      'Error': 'Unexpected error.',
                  }, 400
      

      【讨论】:

        猜你喜欢
        • 2015-02-27
        • 2017-03-31
        • 2013-12-15
        • 2012-07-06
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多