How to return a more meaningful 500 error in a python-eve application

I have code in a python-eve application that retrieves some data from a device and populates a resource when this resource is requested for the first time. Sometimes the code cannot connect to the device successfully. In this case, I would like to return an error message that explains this better, and not just just a 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.

+3
source share
2 answers

All you have to do is use the Flask method 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

If you want to add a custom description:

abort(500, description='My custom abort description')
+3
source

I like to create custom exceptions and raise those that have comment values, for example:

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
0
source

All Articles