Skip to content

fix: 定时任务创建失败时返回错误信息而非静默处理#7513

Open
Hongbro886 wants to merge 1 commit intoAstrBotDevs:masterfrom
Hongbro886:fix/cron-scheduling-error
Open

fix: 定时任务创建失败时返回错误信息而非静默处理#7513
Hongbro886 wants to merge 1 commit intoAstrBotDevs:masterfrom
Hongbro886:fix/cron-scheduling-error

Conversation

@Hongbro886
Copy link
Copy Markdown

@Hongbro886 Hongbro886 commented Apr 13, 2026

fix #7439

Modifications / 改动点

_schedule_job() 原本在调度失败时仅记录错误后静默返回,现改为重新抛出异常;FutureTaskTool.call() 新增 try/except

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

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.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Propagate cron job scheduling failures instead of silently swallowing them and surface a user-visible error message when task creation fails.

Bug Fixes:

  • Return an explicit error message from the cron tool when scheduling a task fails instead of proceeding as if creation succeeded.
  • Re-raise exceptions in the cron manager when scheduling a job fails so errors are not silently ignored.

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Apr 13, 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 2 issues, and left some high level feedback:

  • Catching bare Exception in FutureTaskTool.call makes it harder to distinguish expected scheduling failures from unexpected bugs; consider catching a more specific exception type (or wrapping in a custom error) so callers can react appropriately.
  • Returning the raw exception message directly in the user-facing string (f"error: failed to schedule task: {e}") may leak internal details; consider mapping known failures to clearer, localized messages and logging the detailed error instead.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Catching bare `Exception` in `FutureTaskTool.call` makes it harder to distinguish expected scheduling failures from unexpected bugs; consider catching a more specific exception type (or wrapping in a custom error) so callers can react appropriately.
- Returning the raw exception message directly in the user-facing string (`f"error: failed to schedule task: {e}"`) may leak internal details; consider mapping known failures to clearer, localized messages and logging the detailed error instead.

## Individual Comments

### Comment 1
<location path="astrbot/core/tools/cron_tools.py" line_range="115-124" />
<code_context>
-                run_once=run_once,
-                run_at=run_at_dt,
-            )
+            try:
+                job = await cron_mgr.add_active_job(
+                    name=name,
+                    cron_expression=str(cron_expression) if cron_expression else None,
+                    payload=payload,
+                    description=note,
+                    run_once=run_once,
+                    run_at=run_at_dt,
+                )
+            except Exception as e:
+                return f"error: failed to schedule task: {e}"
             next_run = job.next_run_time or run_at_dt
             suffix = (
</code_context>
<issue_to_address>
**🚨 issue (security):** Catching broad Exception and returning a plain error string may leak details and break return-type expectations.

This path now exposes the raw exception message to users and may also change the return type of `call` from a structured value to a plain string. Please either catch more specific exception types and return a sanitized, generic error message, or re-raise (possibly as a domain-specific exception) so that upstream code can handle formatting and typing consistently.
</issue_to_address>

### Comment 2
<location path="astrbot/core/cron/manager.py" line_range="184-186" />
<code_context>
             )
         except Exception as e:
             logger.error(f"Failed to schedule cron job {job.job_id}: {e!s}")
+            raise

     def _get_next_run_time(self, job_id: str):
</code_context>
<issue_to_address>
**suggestion:** Re-raising after logging at error level may cause duplicated error logs and could use `logger.exception` for better context.

Because `_schedule_job` now re-raises, callers will likely log the failure too, so this `logger.error` risks duplicate top-level error entries and omits the traceback.

To refine this:
- Use `logger.exception("Failed to schedule cron job %s", job.job_id)` if this is the primary logging site, or
- Lower the log level here (or remove this log) and let the caller handle error-level logging.

```suggestion
        except Exception:
            logger.exception("Failed to schedule cron job %s", job.job_id)
            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.

@dosubot dosubot bot added the area:core The bug / feature is about astrbot's core, backend label Apr 13, 2026
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 propagation in the cron job scheduling manager and adds error handling for task creation within the cron tools. The review feedback points out that re-raising exceptions in _schedule_job may inadvertently break the startup synchronization loop for other tasks and suggests extending similar error handling to the task editing operation to ensure robustness against invalid user input.

)
except Exception as e:
logger.error(f"Failed to schedule cron job {job.job_id}: {e!s}")
raise
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.

high

在此处直接 raise 异常虽然能让 add_active_job 等调用者捕获并处理错误,但会破坏 sync_from_db(第 62 行)的逻辑。sync_from_db 在启动时会遍历并加载所有定时任务,如果其中一个任务由于无效的 cron 表达式等原因导致 _schedule_job 抛出异常,整个循环将中断,导致后续的所有任务都无法加载。建议在 sync_from_db 的循环中增加 try...except 保护,以确保单个任务的失败不会影响其他任务的加载。

Comment on lines +115 to +125
try:
job = await cron_mgr.add_active_job(
name=name,
cron_expression=str(cron_expression) if cron_expression else None,
payload=payload,
description=note,
run_once=run_once,
run_at=run_at_dt,
)
except Exception as e:
return f"error: failed to schedule task: {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

这里为 create 操作增加了错误处理。建议也为 edit 操作(约第 201 行)增加类似的 try...except 块。因为 edit 操作调用的 cron_mgr.update_job 内部也会触发 _schedule_job,如果不捕获异常,当用户输入无效的调度配置时,工具执行会直接崩溃,无法返回友好的错误提示。

@Hongbro886 Hongbro886 force-pushed the fix/cron-scheduling-error branch from 9e9e630 to 1a3a42a Compare April 13, 2026 12:17
@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Apr 13, 2026
@Hongbro886 Hongbro886 force-pushed the fix/cron-scheduling-error branch from 1a3a42a to 3dc5e3c Compare April 13, 2026 12:24
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 创建定时任务如果失败,只会静默,AI将不会有反馈,只会在log里打印

1 participant