使用多个例外简化try/except

2024-09-27 00:20:45 发布

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

我有try/except块来处理对某个客户机的API请求。你知道吗

 while attempts < 10:
    try: 
        r = requests.post(server, data=contents,
                          auth=HTTPBasicAuth(service_userid, service_pswd))
        r.raise_for_status()
    except requests.exceptions.HTTPError as errh:
        print ('Http Error:',errh)
        attempts += 1  
        if attempts == 10: 
            body = 'Http Error: ' + str(errh)
            subject = 'Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
    except requests.exceptions.ConnectionError as errc:
        print ('Error Connecting:',errc)
        attempts += 1  
        if attempts == 10: 
            body = 'Error Connecting: ' + str(errh)
            subject = 'Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
    except requests.exceptions.Timeout as errt:
        print ('Timeout Error:',errt)
        attempts += 1  
        if attempts == 10: 
            body = 'Timeout Error: ' + str(errh)
            subject = 'Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
    except requests.exceptions.RequestException as err:
        print ('Unidentified error: ',err)
        attempts += 1  
        if attempts == 10: 
            body = 'Unidentified error: ' + str(errh)
            subject = 'Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)

如何简化上述代码? 一般来说,我想处理HTTP响应错误代码。我只想在同一个电话至少收到10个错误代码的情况下发送一封包含特定错误信息的电子邮件。你知道吗


Tags: iffailureasbodyerrorrequestsexceptionssubject
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:45

由于要执行的操作在每种情况下都是相同的,所以只需将异常分组为单个异常,然后根据错误类/类名自定义消息:

    except (requests.exceptions.HTTPError,requests.exceptions.ConnectionError,requests.exceptions.RequestException,requests.exceptions.Timeout) as err:
        error_message = "{}: ".format(err.__class__.__name__,err)
        print (error_message)
        attempts += 1  
        if attempts == 10: 
            body = error_message
            subject = 'Failure'
            sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)

如果需要间接寻址,只需创建一个dictionary类名=>;string/action to perform/whatever。你知道吗

相关问题 更多 >

    热门问题