简体   繁体   中英

How to catch a github exception

Im trying to get commits from Github. But i run into a 409 error, i want to retry after it fails. Im thinking the problem is with not catching the error correctly from GithubExceptions.

df_commits = pd.DataFrame(columns=['repo', 'commits', 'user' , 'created_at'])
    for repo in org.get_repos():
commits = repo.get_commits(since=datetime(2022, 9, 1))
for commits in commits:
    try:
        df_commits = df_commits.append({'repo': repo.name, 'commits': commits, 'user' : 
   commits.author, 'created_at' : commits.commit.author.date}, ignore_index=True)
    except:
        GithubException == 409
        print(GithubException)
        continue
Traceback (most recent call last):
  File "c:\Users\Q4V\Documents\VanOordProjects\Github\commits.py", line 16, in <module>
    for commits in commits:
  File "C:\Users\Q4V\AppData\Local\Programs\Python\Python310\lib\site-packages\github\PaginatedList.py", line 56, in __iter__
    newElements = self._grow()
  File "C:\Users\Q4V\AppData\Local\Programs\Python\Python310\lib\site-packages\github\PaginatedList.py", line 67, in _grow
    newElements = self._fetchNextPage()
  File "C:\Users\Q4V\AppData\Local\Programs\Python\Python310\lib\site-packages\github\PaginatedList.py", line 199, in _fetchNextPage
    headers, data = self.__requester.requestJsonAndCheck(
  File "C:\Users\Q4V\AppData\Local\Programs\Python\Python310\lib\site-packages\github\Requester.py", line 
353, in requestJsonAndCheck
    return self.__check(
  File "C:\Users\Q4V\AppData\Local\Programs\Python\Python310\lib\site-packages\github\Requester.py", line 
378, in __check
    raise self.__createException(status, responseHeaders, output)
github.GithubException.GithubException: 409 {"message": "Git Repository is empty.", "documentation_url": "https://docs.github.com/rest/commits/commits#list-commits"}

There are several ways of catching exceptions. I will make just two examples below. Please read more on how to properly use the try/except block. The problem with your code is that GithubException, as you typed it, is just a variable name, probably not even defined.

You can try:

for commit in commits:
    try:
        ...
    except Exception as e:
        print(f'got Exception {e}')
        continue

The block below will catch any exception and continue.

You can be more sophisticated and check the traceback to continue only if a particular error message is given.

import traceback


for commit in commits:
    try:
        ...
    except Exception as e:
        tb = traceback.format_exc()
        if 'Git Repository is empty' in tb:
            print(f'The repo is empty!')
            continue
        else:
            ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM