处理googleapi客户端错误

问题描述 投票:0回答:1

我正在通过Google Calendar API阅读并为一组电子邮件创建日历事件。现在,如果我提供一个电子邮件ID错误,则会引发错误。

googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.goo
gleapis.com/calendar/v3/calendars/xxx%40gmail.com/events?timeMin=2019-1
2-18T00%3A00%3A00%2B05%3A30&maxResults=240&timeMax=2019-12-18T23%3A59%3A00%2B05%
3A30&singleEvents=true&orderBy=startTime&alt=json returned "Not Found">

我可以理解电子邮件中有错误,并且出现此错误。但是我想处理这种异常,例如如果我的电子邮件有误,它也应该跳过错误的电子邮件,并且应该走得更远并显示正确的结果。

我尝试过的是

from googleapiclient.errors import HttpError

def my_funtion():

        try:
            ----
            -----
        except HttpError as err:
            print("The exception is",err)
        finally:
            return "I am returning whatever i get it from try

是正确的try catch块吗?对于上面的代码,我得到相同的googleclientapi错误,它不在excpet块内

我期望这里是它应转到try块,如果其中一个电子邮件ID错误,则应跳过该电子邮件ID,并应返回从try块中获取的任何内容的结果。我可以说它应该省略apiclient但返回结果。

#for calendar_id in calendar_ids:    
    eventsResult = service.events().list(calendarId=["[email protected]","[email protected]","[email protected]"],timeMin=start_date,timeMax=end_date,singleEvents=True,orderBy='startTime').execute()
    events = eventsResult.get('items', [])
    if not events:
        print('No upcoming events found.')
    print(events)
    while True:
        for event in events.get('items', []):
            print(event['summary'])
        page_token = events.get('nextPageToken') #check if any event present in next page of the calendar
        if page_token:
            events = service.events().list(calendarId='primary', pageToken=page_token).execute()
        else:
            break

    for calendar_id in calendar_ids:
        count = 0
        print('\n----%s:\n' % calendar_id)
        try:
            eventsResult = service.events().list(
                calendarId=calendar_id,
                timeMin=start_date,
                timeMax=end_date,
                singleEvents=True,
                orderBy='startTime').execute()
            events = eventsResult.get('items', [])
            if not events:
                print('No upcoming events found.')
            for event in events:
                if 'summary' in event:
                    if 'PTO' in event['summary']:
                        count += 1
                        start = event['start'].get(
                            'dateTime', event['start'].get('date'))
                        print(start, event['summary'])
        except exception as err:
            print("I am executing",err)
        finally:
            print('Total days off for %s is %d' % (calendar_id, count))```

python exception google-calendar-api
1个回答
0
投票

我已经获得了这篇文章的答案。我在异常块中使用了“通过”,它运行良好。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.