Question

I have some code in a python-eve app that retrieves some data from a device and populates a resource when that resource is requested for the first time. Sometimes the code can't successfully connect to the device. In this case, I would like to return an error message that explains this better, rather than just a plain 500 error. Here is the on_fetch_item hook:

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

Thanks in advance.

Was it helpful?

Solution

All you have to do is take advantage of Flask's abort method:

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

If you want to add a custom description:

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

OTHER TIPS

I like to create custom exceptions, and raise those with meaning comments, Eg:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top