如何用Python函数显示不同的错误消息

2024-04-29 09:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码工作正常,除非我想显示相应的错误消息。例如,如果脚本无法连接到Consul,我想显示一个错误来说明这一点。另一方面,如果密钥(Jira票号)在Consul中不存在,我希望它显示不同的消息。你知道吗

从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

运行的函数(代码段)

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

Main(代码段)

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

Tags: key函数modules消息datareturnif错误
1条回答
网友
1楼 · 发布于 2024-04-29 09:58:44

您已经在deployme中捕获了异常。因此,在你的主要你永远不会抓住例外,你正在寻找。相反,您想要做的是raise,这样您就可以捕捉到一些东西。你知道吗

另外,正如@gill在他们的评论中明确指出的那样,由于您的错误很可能发生在getDeployList方法中,因此您应该在那里提出并从deployme中删除try/except。这将允许您保持退出状态,如果有任何对getDeployList的调用出现,它将被捕获在__main__代码中。你知道吗

另外,创建自定义异常(或从您使用的模块引发异常):

class MyCustomException(Exception):
    pass

getDeployList方法中引发自定义异常:

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

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

然后在main中捕获异常。应该有用的

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

相关问题 更多 >