> For the complete documentation index, see [llms.txt](https://zhouhao4221.gitbook.io/haiqing-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/error-diagnosis.md).

# 错误诊断

遇到错误但无法快速定位根因时使用。适合运行时报错、测试失败、AI 多轮生成后输出仍与预期不符的情况。

***

## 什么时候用

* 有明确的错误信息或堆栈，但看不出根因
* AI 生成的代码反复修改还是跑不通
* 某个行为和预期不符，但没有明确报错

不适合：并发问题、时序相关 bug——这类问题需要结合运行时日志和监控数据，不适合单纯靠代码分析。

## 准备什么

* **错误信息**：完整的错误信息或堆栈（stack trace），不要只截图关键行
* **相关代码**：出错的函数或模块，必要时包含调用方
* **预期行为**：这段代码应该做什么，实际做了什么
* **上下文**（可选）：调用方式、输入数据、环境信息。有了这些，AI 的诊断从"可能是"变成"是"

给不完整的堆栈是最常见的问题。AI 看到截断的堆栈时，会给出假设而不是结论。

## 怎么触发

**单次任务**

```
先读 04-prompt/code/error-diagnosis.md，
错误信息：[粘贴完整堆栈]，
相关代码在 [文件路径]，
预期行为：[描述]，
上下文：[调用方式 / 输入数据]。
请诊断根本原因。
```

## 好的输出是什么样的

* 第一句就是根本原因，不是"可能是 X 问题"
* 原因分析解释为什么会发生，而不只是描述发生了什么
* 给出 1-3 个修复选项，说明各自的权衡，而不只是一个"你应该这样做"
* 明确说明如何验证修复是否有效
* 如果信息不足，先列出需要哪些额外信息，再给最可能的假设

根本原因和表象的区别："空指针异常"是表象，"调用方在 X 未初始化时就调用了 Y 方法"才是根本原因。

## 常见失败模式

* **得到假设而不是结论**：给的信息不完整，AI 只能猜。确保堆栈完整、相关代码都给了
* **修复了表象**：AI 给出的修复加了 nil 检查而不是解决初始化问题。如果修复方案看起来像打补丁，要求 AI 解释根本原因
* **并发问题误判**：时序相关的 bug 在静态代码里看不出来。这类问题告诉 AI 加日志点，而不是让它直接给修复方案
* **循环修改陷阱**：AI 改了 A 又引入了 B，再改 B 又影响了 A。出现这种情况，退出循环，重新描述预期行为，从头开始

***

## 版本历史

* v1.0：初始版本


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/error-diagnosis.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
