# HelloGitHub Bot GitHub API Error Handling: Timeouts and Failure Recovery

> Learn how the HelloGitHub bot handles GitHub API errors, including timeouts and failure recovery strategies. Discover its approach to ensuring reliable operation.

- Repository: [削微寒/HelloGitHub](https://github.com/521xueweihan/HelloGitHub)
- Tags: how-to-guide
- Published: 2026-02-25

---

**The HelloGitHub bot implements two defensive strategies in [`script/github_bot/github_bot.py`](https://github.com/521xueweihan/HelloGitHub/blob/main/script/github_bot/github_bot.py): it validates HTTP status codes for event requests to return empty lists on failure, and wraps repository star count requests in try/except blocks with a 2‑second timeout, returning `-1` to indicate unknown star counts while logging all errors to [`bot_log.txt`](https://github.com/521xueweihan/HelloGitHub/blob/main/bot_log.txt).**

The HelloGitHub project relies on its Python bot to interact with GitHub's REST API for fetching user events and repository metadata. Located in [`script/github_bot/github_bot.py`](https://github.com/521xueweihan/HelloGitHub/blob/main/script/github_bot/github_bot.py), the bot’s error handling mechanisms ensure that temporary API failures or network timeouts do not crash the application or halt content processing.

## Status Code Validation for Event Requests

When fetching received events from the `GET https://api.github.com/users/{username}/received_events` endpoint, the bot validates the HTTP response before processing data. The `get_data()` function (lines 79‑87) uses `requests.get` to execute the call, then checks if `response.status_code == 200`.

If the API returns any non‑200 status code, the bot logs the error via `logging.error()` and returns an empty list `[]` as a graceful fallback. This prevents the bot from crashing when rate limits are hit or the API is temporarily unavailable.

```python
def get_data(page=1):
    response = requests.get(API['events'] + f'?page={page}',
                            auth=(ACCOUNT['username'], ACCOUNT['password']))
    if response.status_code == 200:                 # ✅ success

        return response.json()
    else:                                           # ❌ non‑200 response

        logging.error('请求 event api 失败：', response.status_code)
        return []                                   # graceful fallback

```

## Timeout and Exception Handling for Repository Stars

For fetching repository star counts, the bot employs a more aggressive defensive strategy in the `get_stars()` function (lines 148‑156). Each request includes a **2‑second timeout** parameter and is wrapped in a try/except block that catches all exceptions, including timeouts, DNS failures, and connection errors.

When any exception occurs, the bot assigns a star count of **-1** to indicate the data is unavailable, logs a warning via `logger.warning()`, and continues processing the remaining repositories without interruption.

```python
def get_stars(data):
    for fi_data in data:
        project_info = {}
        try:
            # 2‑second timeout, any network error raises an exception

            repo_stars = requests.get(fi_data['repo']['url'],
                                      timeout=2).json()
            project_info['repo_stars'] = int(repo_stars['stargazers_count'])
        except Exception as e:                     # ✅ catches timeout, DNS errors, etc.

            project_info['repo_stars'] = -1
            logger.warning(u'获取：{} 项目星数失败——{}'.format(
                project_info['repo_name'], e))
        # … continue processing the rest of the repo list

```

## Graceful Degradation and Logging Strategy

The HelloGitHub bot treats API failures as expected operational conditions rather than critical errors. By returning **empty lists** for failed event fetches and **-1** for unavailable star counts, the bot maintains its processing pipeline while clearly marking missing data.

All failures are recorded in the runtime-generated [`script/github_bot/bot_log.txt`](https://github.com/521xueweihan/HelloGitHub/blob/main/script/github_bot/bot_log.txt) file. The system distinguishes between **errors** (for failed event API calls) and **warnings** (for individual repository star fetch failures), providing clear visibility into which data sources are unreliable.

## Summary

- **Status code validation:** The bot checks for HTTP 200 responses when fetching events, returning empty lists and logging errors for any other status.
- **Timeout protection:** Repository star requests enforce a strict 2‑second timeout to prevent hanging on slow connections.
- **Exception swallowing:** All network exceptions are caught in `get_stars()`, allowing the bot to continue processing other repositories.
- **Sentinel values:** The bot uses `[]` and `-1` as fallback values to indicate missing event data and unknown star counts respectively.
- **Comprehensive logging:** Both errors and warnings are written to [`bot_log.txt`](https://github.com/521xueweihan/HelloGitHub/blob/main/bot_log.txt) for operational monitoring.

## Frequently Asked Questions

### What happens when the GitHub API returns a non‑200 status code for event requests?

When the received events endpoint returns any status code other than 200, the `get_data()` function logs the error via `logging.error()` and returns an empty Python list `[]`. This allows the bot to continue execution without crashing while signaling that no events were retrieved for that cycle.

### How does the HelloGitHub bot handle network timeouts?

The bot explicitly sets a **2‑second timeout** on all repository star count requests in the `get_stars()` function. If the `requests.get()` call exceeds this duration or encounters any network error, the exception is caught and the star count is set to **-1** to indicate the data is unavailable.

### Why does the bot return -1 for star counts instead of 0 or None?

The value **-1** serves as a sentinel indicating a fetch failure or timeout, distinguishing between a repository that genuinely has zero stars and one where the star count could not be retrieved due to API errors or network issues. This distinction helps maintainers identify which entries need manual review.

### Where are API errors logged in the HelloGitHub project?

Both error types are written to [`script/github_bot/bot_log.txt`](https://github.com/521xueweihan/HelloGitHub/blob/main/script/github_bot/bot_log.txt) at runtime. Failed event requests generate **error** level logs via `logging.error()`, while repository star fetch failures generate **warning** level logs via `logger.warning()`, creating a persistent record of API reliability issues.