Skip to content

fix: 配置文件加载失败的时候输出详情 #8204#8230

Open
IITII wants to merge 1 commit into
AstrBotDevs:masterfrom
IITII:catch_config_file_err
Open

fix: 配置文件加载失败的时候输出详情 #8204#8230
IITII wants to merge 1 commit into
AstrBotDevs:masterfrom
IITII:catch_config_file_err

Conversation

@IITII
Copy link
Copy Markdown

@IITII IITII commented May 18, 2026

TODO: 不清楚空配置文件的情况下, 应该载入默认配置还是直接抛异常, 目前是直接抛异常.

如果, 修复对应配置文件之后还是无法登陆, 可能是 webui 版本不一致导致的. 手动下载替换 ./data/dist 文件夹
https://github.com/AstrBotDevs/AstrBot/releases/
https://docs.astrbot.app/use/webui.html#%E6%9B%B4%E6%96%B0%E7%AE%A1%E7%90%86%E9%9D%A2%E6%9D%BF

(所以是究竟哪里自动更新了, 导致旧版本重启之后问题不断吗,,,

Modifications / 改动点

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

* 某些情况下重启 AstrBot 后, 文件 /AstrBot/data/cmd_config.json 可能为空
@auto-assign auto-assign Bot requested review from Fridemn and LIghtJUNction May 18, 2026 18:47
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. area:core The bug / feature is about astrbot's core, backend labels May 18, 2026
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • When checking for an empty config file, consider using if not conf_str.strip(): so files with only whitespace/newlines are also treated as empty rather than causing a JSON parse error.
  • Instead of raise e after logging, use a bare raise to preserve the original traceback and make debugging easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- When checking for an empty config file, consider using `if not conf_str.strip():` so files with only whitespace/newlines are also treated as empty rather than causing a JSON parse error.
- Instead of `raise e` after logging, use a bare `raise` to preserve the original traceback and make debugging easier.

## Individual Comments

### Comment 1
<location path="astrbot/core/config/astrbot_config.py" line_range="69-71" />
<code_context>
+                raise EnvironmentError(f'文件 {config_path} 为空, 请手动处理...')
+            try:
+                conf = json.loads(conf_str)
+            except Exception as e:
+                logger.error(f'读取文件失败 {config_path}: {e}')
+                raise e
         dashboard_conf = conf.get("dashboard")
         legacy_dashboard_password_change_required = bool(
</code_context>
<issue_to_address>
**issue:** Re-raising the caught exception with `raise e` drops the original traceback context.

`raise e` overwrites the original traceback and loses the full stack context. Use a bare `raise` to preserve the original traceback while keeping the logging as-is:

```python
            except Exception as e:
                logger.error(f'读取文件失败 {config_path}: {e}')
                raise
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +69 to +71
except Exception as e:
logger.error(f'读取文件失败 {config_path}: {e}')
raise e
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Re-raising the caught exception with raise e drops the original traceback context.

raise e overwrites the original traceback and loses the full stack context. Use a bare raise to preserve the original traceback while keeping the logging as-is:

            except Exception as e:
                logger.error(f'读取文件失败 {config_path}: {e}')
                raise

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces error handling for empty or malformed configuration files in astrbot_config.py. The feedback suggests using more appropriate exception types like ValueError instead of EnvironmentError, catching specific json.JSONDecodeError exceptions, and using a bare raise to preserve stack traces. Additionally, it is recommended to consider automatic recovery with default configurations and to include unit tests for these new logic paths.

Comment on lines +65 to +66
if not conf_str:
raise EnvironmentError(f'文件 {config_path} 为空, 请手动处理...')
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

使用 EnvironmentError (OSError 的别名) 来描述文件内容为空可能不太准确。OSError 通常用于系统级错误 (如权限不足、磁盘故障)。对于文件内容不符合预期的情况,建议使用 ValueError 或 RuntimeError。

另外,针对您在 PR 描述中提到的 TODO:考虑到机器人已经具备在配置文件不存在时自动生成默认配置的能力,当文件为空 (通常是由于异常中断导致的损坏) 时,自动载入默认配置并记录警告日志可能是一个更健壮的处理方式,可以避免机器人因配置文件损坏而无法启动。此外,建议后续优化 save_config 方法,采用“先写临时文件再重命名”的原子化写入策略,从根本上避免此类损坏。最后,请确保这些配置处理逻辑的变更附带相应的单元测试。

References
  1. Use ValueError or RuntimeError for errors related to the content of a file rather than system-level errors. (link)
  2. New functionality should be accompanied by corresponding unit tests.

Comment on lines +67 to +71
try:
conf = json.loads(conf_str)
except Exception as e:
logger.error(f'读取文件失败 {config_path}: {e}')
raise e
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

建议捕获更具体的 json.JSONDecodeError 异常,并使用 raise 代替 raise e 以保持完整的异常堆栈信息。

Suggested change
try:
conf = json.loads(conf_str)
except Exception as e:
logger.error(f'读取文件失败 {config_path}: {e}')
raise e
try:
conf = json.loads(conf_str)
except json.JSONDecodeError as e:
logger.error(f'读取文件失败 {config_path}: {e}')
raise
References
  1. Use raise without an exception object to re-raise the current exception and preserve the stack trace. (link)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant