sdot257
sdot257

Reputation: 10366

How to display different error message with Python functions

My code works correctly except I would like to display the appropriate error message. For example, if the script can't connect to Consul, I want to display an error stating this. On the other hand, if the key (Jira ticket number) doesn't exist within Consul, I want it to display a different message.

Function to get key/value from Consul

def getDeployList(jira_ticket):
    try:
        c = consul.Consul(config.get('consul','consul_server'))
        modules=[]
        module_key=[]
        index, data = c.kv.get('deploylist/'+jira_ticket,  recurse=True)
        if data:
            for s in data:
                if s['Value'] is not None:
                    key = s['Key'].split('/')[2]
                    modules.append(key + " - " + s['Value'])
                    module_key.append(key)
            return (module_key,modules)
        else:
            return False
    except:
        return False

Function that runs (snippet)

def deployme(obj):
    try:
        module_key,modules = getDeployList(jira_ticket)
    except Exception:
        quit()

Main (snippet)

if __name__ == '__main__':
    while True:
        job = beanstalk.reserve()
        try:
            deployme(decode_json)
        except:
            print "There's an issue retrieving the JIRA ticket!"
        job.delete()

Upvotes: 4

Views: 1042

Answers (1)

idjaw
idjaw

Reputation: 26570

You are already catching your exception in deployme. So in your main you will never catch the exception you are looking for. Instead, what you want to do is raise so you can catch something.

Also, as @gill made it clear in their comment, since your errors are most likely happening in your getDeployList method, you should raise there and remove the try/except from deployme. This will allow you keep that quit, and if any call to getDeployList raises, it will be caught in your __main__ code.

Also, create a custom exception (or raise an exception from the module you are using):

class MyCustomException(Exception):
    pass

Raise your custom exception in your getDeployList method:

def getDeployList(jira_ticket):
    # logic
    raise MyCustomException()

def deployme(obj):
    module_key,modules = getDeployList(jira_ticket)

Then you catch your exception in main. It should work

if __name__ == '__main__':
    try:
        deployme(decode_json)
    except MyCustomException:
        print "There's an issue retrieving the JIRA ticket!"

Upvotes: 3

Related Questions