How to display various error messages with Python functions

My code works correctly, except that I would like to display the corresponding error message. For example, if the script cannot connect to Consul, I want to show an error message. On the other hand, if the key (Jira ticket number) does not exist in Consul, I want it to display another message.

Consul Key / Value Function

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 Performed (fragment)

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

Main (fragment)

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

You have already selected your exception in deployme. Thus, in your core, you will never catch the exception you are looking for. Instead, you need raiseto be able to catch something.

, @gill , , , getDeployList, try/except deployme. , - getDeployList , __main__.

( , ):

class MyCustomException(Exception):
    pass

getDeployList:

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

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

.

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

Source: https://habr.com/ru/post/1630095/


All Articles