簡體   English   中英

如何在python-eve應用程序中返回更有意義的500錯誤

[英]How to return a more meaningful 500 error in a python-eve app

我在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

提前致謝。

您所要做的就是利用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')

我喜歡創建自定義異常,並提出具有意義注釋的異常,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM