如何在python-eve应用程序中返回更有意义的500错误

时间:2014-02-20 18:41:46

标签: python eve

我在python-eve应用程序中有一些代码,它从设备检索一些数据,并在第一次请求该资源时填充资源。有时代码无法成功连接到设备。在这种情况下,我想返回一条更好地解释这一点的错误消息,而不仅仅是一个普通的500错误。这是on_fetch_item钩子:

def before_returning_item(resource, _id, document):
if resource == "switches":
    if "interfaces" not in document.keys():
        # retrieve and store switch config if it hasn't been stored yet
        r = app.data.driver.db[resource]
        try:
            switch = prepare_switch_from_document(document)
        except socket.timeout:
            # raise some more meaningful error with message
            pass
        interface_list = switch.get_formatted_interfaces()
        r.update({'_id': _id}, {'interfaces': interface_list})
        document['interfaces'] = interface_list

app.on_fetch_item += before_returning_item

提前致谢。

2 个答案:

答案 0 :(得分:4)

您所要做的就是利用Flask的abort方法:

from flask import abort

def before_returning_item(resource, _id, document):
    if resource == "switches":
        if "interfaces" not in document.keys():
            # retrieve and store switch config if it hasn't been stored yet
            r = app.data.driver.db[resource]
            try:
                switch = prepare_switch_from_document(document)
            except socket.timeout:
                # raise some more meaningful error with message
                abort(500)
            interface_list = switch.get_formatted_interfaces()
            r.update({'_id': _id}, {'interfaces': interface_list})
            document['interfaces'] = interface_list

    app.on_fetch_item += before_returning_item

如果您想添加自定义说明:

abort(500, description='My custom abort description')

答案 1 :(得分:-1)

我喜欢创建自定义异常,并提出具有意义注释的异常,例如:

class MyExcept(Exception): pass

def before_returning_item():
    ...
    if error_condition:
        raise MyException('detailed explanation')
    ...

try:
    before_returning_item()
except MyException, exc:
    if 'device not ready' in str(exc):
        print("Device was not rdy...Try agin?")
    else:
        raise