python调用外部api返回数据错误,使用Python和Flask返回API错误消息

I am designing a RESTful API using Python and Flask. As expected, the API needs to receive an API request and return data if all goes well, but in the instance of an error, it needs to fail softly and return the proper error. I typically raise exceptions when an error results, but in this case I need to return the error message to the user (try-catch block?).

The way I am currently dealing with errors is to have my functions return both the data and an error, and to check for the data at each level, finally returning either the data or the error to the caller of the API function.

The problem with this is that it can get cumbersome when there are several levels of function calls, requiring my functions to pass data and errors several times and perform checks each time.

Is there a better way to do this? What are some improvements I could make to make the error propagation more simple and elegant?

Here is an example of the way I'm currently returning errors:

def get_data()

data1, error = get_some_data() # function not shown

if data1 is None:

return None, "could not retrieve data1"

data2, error = get_some_other_data() # function not shown

if data2 is None:

return None, "could not retrieve data2"

return (data1, data2), None

@app.route("/api/method", methods=['GET'])

def method():

data, error = get_data()

if data is None:

if error is None:

error = "unknown error"

return json.dumps({ "error": error }), 500

return json.dumps({ "data": data }), 200

解决方案

You could use abort(http_code) to return an appropriate http code to the client or just raise a non-http exception. And use @app.errorhandler() decorator to provide a custom handler for http errors and arbitrary exceptions. You could also use an ordinary try/except block where you are ready to handle an exception. Python is not Go you can use exceptions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值