Frappe Errors Controllers 标志

Frappe Errors Controllers

组织
Impertio-Studio
frappe-errors-controllers

Use when debugging or preventing errors in Frappe Document Controllers. Prevents autoname failures, validate loops, on_submit without is_submittable, wrong lifecycle hook choice, get_list permission errors, NestedSet errors, extend_doctype_class conflicts, missing super() calls, and recursion without flags. Covers error diagnosis by lifecycle phase for v14/v15/v16. Keywords: controller error, autoname, validate loop, on_submit, is_submittable,, save fails, validate error, on_submit not working, autoname broken, controller crash. get_list, NestedSet, extend_doctype_class, super, flags, recursion guard.

概览

发布者Impertio-Studio
代码仓库Frappe_Claude_Skill_Package
技能名称frappe-errors-controllers
星标数
180
复刻数
53
附带文件
3
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 3 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 Impertio-Studio 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Frappe Errors Controllers AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package/tree/main/skills/source/errors/frappe-errors-controllers
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package.git /tmp/Frappe_Claude_Skill_Package
mkdir -p .claude/skills
cp -r /tmp/Frappe_Claude_Skill_Package/skills/source/errors/frappe-errors-controllers .claude/skills/frappe-errors-controllers
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Frappe Errors Controllers,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Frappe Errors Controllers。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Frappe Errors Controllers 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Controller Errors — Diagnosis and Resolution

Cross-refs: frappe-syntax-controllers (syntax), frappe-impl-controllers (workflows), frappe-errors-serverscripts (server scripts).


Error Diagnosis by Lifecycle Phase

CONTROLLER ERROR
│
├─► NAMING PHASE (autoname / before_naming)
│   ├─► NamingSeries not set → Add naming_series field or autoname property
│   ├─► DuplicateEntryError → Name collision, check uniqueness
│   └─► "name cannot be set directly" → Use autoname method, not self.name = x
│
├─► VALIDATION PHASE (before_validate / validate / before_save)
│   ├─► Infinite recursion → doc.save() called inside validate
│   ├─► Validation skipped → Missing super().validate() in override
│   └─► Wrong error timing → Use validate, not on_update, to block save
│
├─► SAVE PHASE (before_save / on_update / after_insert)
│   ├─► Changes lost in on_update → Use db_set(), not self.field = x
│   ├─► Infinite loop → self.save() in on_update triggers on_update again
│   └─► Transaction broken → frappe.db.commit() in controller (DON'T)
│
├─► SUBMIT PHASE (before_submit / on_submit)
│   ├─► "Not allowed to submit" → DocType missing is_submittable = 1
│   ├─► Partial state → Validation in on_submit (too late, already submitted)
│   └─► Stock/GL failures → Entries fail but docstatus already = 1
│
├─► CANCEL PHASE (before_cancel / on_cancel)
│   ├─► "Cannot cancel: linked docs" → Check and handle linked documents
│   └─► Partial cleanup → One reversal fails, rest skipped
│
└─► PERMISSION PHASE (has_permission / get_list)
    ├─► "Not permitted" → has_permission returns None (should be True/False)
    ├─► get_list returns nothing → permission_query_conditions SQL error
    └─► SQL injection → User input in conditions without escape

Error Message → Cause → Fix Table

Error MessageCauseFix
NamingSeries is not setDocType uses naming_series but field is missingAdd naming_series field to DocType or set autoname in controller
DuplicateEntryErrorautoname generated non-unique nameUse naming_series with counter, or add hash suffix
Maximum recursion depth exceededself.save() called in validate/on_updateNEVER call self.save() in hooks; use self.db_set() in on_update
Not allowed to submitDocType lacks is_submittable = 1Enable "Is Submittable" in DocType settings
Cannot cancel: linked docs existSubmitted linked documents block cancellationCancel linked docs first, or use before_cancel to check
AttributeError: super()Missing super() call in overridden hookALWAYS call super().method_name() first in overrides
Value missing for: fieldController validate skipped parent logicEnsure super().validate() is called
frappe.db.commit() breaks transactionsManual commit in controller hookNEVER call frappe.db.commit() in controllers
Changes lost in on_updateSet self.field = x instead of self.db_set()Use self.db_set("field", value) after save hooks
NestedSet: root cannot be childParent set to itself or circular referenceValidate parent != self in validate, check lft/rgt
extend_doctype_class conflict [v16+]Multiple apps extend same class with conflicting methodsUse MRO-aware design, check method resolution order
has_permission returns wrong resultFunction returns None instead of True/FalseALWAYS return explicit True or False
permission_query_conditions SQL errorMalformed WHERE clause fragmentTest conditions string independently, use frappe.db.escape()

Critical Error Patterns

1. Autoname Failures

python
# ❌ WRONG — Setting name directly fails
class CustomDoc(Document):
    def autoname(self):
        self.name = f"DOC-{self.customer}"  # May cause DuplicateEntryError

# ✅ CORRECT — Use naming utilities
class CustomDoc(Document):
    def autoname(self):
        # Option 1: Naming series
        from frappe.model.naming import set_name_by_naming_series
        set_name_by_naming_series(self)

        # Option 2: Safe format with counter
        self.name = frappe.model.naming.make_autoname(
            f"DOC-.{self.customer}.-.####"
        )

        # Option 3: Hash for guaranteed uniqueness
        # Set autoname = "hash" in DocType JSON instead

Autoname options: naming_series, field:fieldname, format:PREFIX-{fieldname}-.####, hash, Prompt, or custom autoname() method.

2. Validate Loop: self.save() in Hooks

python
# ❌ WRONG — Infinite recursion
class SalesOrder(Document):
    def validate(self):
        self.calculate_totals()
        self.save()  # Triggers validate again → infinite loop!

    def on_update(self):
        self.status = "Updated"
        self.save()  # Triggers on_update again → infinite loop!

# ✅ CORRECT — Framework handles save; use db_set after save
class SalesOrder(Document):
    def validate(self):
        self.calculate_totals()
        # No save() — framework saves after validate completes

    def on_update(self):
        self.db_set("status", "Updated")  # Direct DB write, no trigger

3. on_submit Without is_submittable

python
# ❌ ERROR — "Not allowed to submit"
class MyDoc(Document):
    def on_submit(self):
        self.create_entries()
# This fails if DocType JSON lacks: "is_submittable": 1

# ✅ FIX — Enable in DocType definition
# In my_doc.json:
# { "is_submittable": 1 }
# Then before_submit and on_submit hooks work

4. Wrong Lifecycle Hook: Error Timing

python
# ❌ WRONG — Validation in on_submit (document already submitted!)
class SalesOrder(Document):
    def on_submit(self):
        if not self.has_stock():
            frappe.throw(_("Insufficient stock"))  # docstatus already = 1!

# ✅ CORRECT — ALWAYS validate in before_submit
class SalesOrder(Document):
    def before_submit(self):
        if not self.has_stock():
            frappe.throw(_("Insufficient stock"))  # Clean abort, stays Draft

    def on_submit(self):
        self.create_stock_entries()  # Only post-submit actions here

Transaction Rollback Rules by Hook:

Hookfrappe.throw() Effect
validate / before_saveFull rollback — document NOT saved
before_submitFull rollback — stays Draft
before_cancelFull rollback — stays Submitted
on_update / after_insertDocument IS saved — error shown but doc persists
on_submitdocstatus = 1 — error shown but ALREADY submitted
on_canceldocstatus = 2 — error shown but ALREADY cancelled

5. Missing super() in Overrides

python
# ❌ WRONG — Parent validation completely skipped
from erpnext.selling.doctype.sales_order.sales_order import SalesOrder

class CustomSalesOrder(SalesOrder):
    def validate(self):
        # Parent validate() never runs! All ERPNext validations bypassed!
        self.custom_check()

# ✅ CORRECT — ALWAYS call super() first
class CustomSalesOrder(SalesOrder):
    def validate(self):
        super().validate()  # Run all parent validations first
        self.custom_check()  # Then add custom logic

6. extend_doctype_class [v16+]

python
# In hooks.py — v16+ preferred approach
extend_doctype_class = {
    "Sales Order": ["myapp.overrides.sales_order.SalesOrderMixin"]
}

# myapp/overrides/sales_order.py
class SalesOrderMixin:
    """Mixin class — extends, does not replace."""
    def validate(self):
        super().validate()  # ALWAYS call super — runs original + other mixins
        self.custom_validation()

Resolution order: class ExtendedSalesOrder(Mixin2, Mixin1, OriginalSalesOrder) — last mixin listed has highest priority.

7. Flags for Recursion Guard

python
# ❌ WRONG — on_update of linked doc triggers this doc's on_update
class SalesOrder(Document):
    def on_update(self):
        self.update_quotation()  # Quotation.on_update triggers back here

# ✅ CORRECT — Use flags to prevent recursion
class SalesOrder(Document):
    def on_update(self):
        if self.flags.get("skip_linked_update"):
            return
        self.flags.skip_linked_update = True
        self.update_quotation()

    def update_quotation(self):
        if self.quotation:
            q = frappe.get_doc("Quotation", self.quotation)
            q.flags.skip_linked_update = True  # Prevent back-trigger
            q.db_set("status", "Ordered")

8. get_list Permission Errors

python
# ❌ WRONG — permission_query_conditions returns None (fallback to no filter)
def get_permission_query(user):
    pass  # Returns None — shows ALL records!

# ❌ WRONG — SQL injection
def get_permission_query(user):
    dept = frappe.db.get_value("User", user, "department")
    return f"department = '{dept}'"  # INJECTION RISK

# ✅ CORRECT — Explicit conditions with escape
def get_permission_query(user):
    if "System Manager" in frappe.get_roles(user):
        return ""  # No filter — full access
    dept = frappe.db.get_value("User", user, "department")
    if dept:
        return f"department = {frappe.db.escape(dept)}"
    return "owner = {0}".format(frappe.db.escape(user))

Note: permission_query_conditions affects frappe.db.get_list() only, NOT frappe.db.get_all().

9. NestedSet Errors

python
# ❌ WRONG — Circular reference causes lft/rgt corruption
class Territory(NestedSet):
    def validate(self):
        # No parent validation!
        pass

# ✅ CORRECT — Validate parent chain
class Territory(NestedSet):
    def validate(self):
        super().validate()
        if self.parent_territory == self.name:
            frappe.throw(_("Territory cannot be its own parent"))
        # NestedSet.validate() checks circular refs automatically
        # but explicit check gives better error message

on_cancel: Isolate Cleanup Operations

python
# ❌ WRONG — First failure stops all cleanup
def on_cancel(self):
    self.reverse_stock()     # If this fails...
    self.reverse_gl()        # ...this never runs
    self.update_linked()     # ...neither does this

# ✅ CORRECT — Isolate each reversal
def on_cancel(self):
    errors = []
    for operation, label in [
        (self.reverse_stock, "Stock reversal"),
        (self.reverse_gl, "GL reversal"),
        (self.update_linked, "Linked docs"),
    ]:
        try:
            operation()
        except Exception as e:
            errors.append(f"{label}: {str(e)}")
            frappe.log_error(frappe.get_traceback(), f"{label} Error")

    if errors:
        frappe.msgprint(
            _("Cancelled with errors:<br>{0}").format("<br>".join(errors)),
            indicator="orange"
        )

ALWAYS / NEVER Rules

ALWAYS

  1. Call super().method() in overridden hooks — Preserve parent logic
  2. Validate in before_submit not on_submit — Last clean abort point
  3. Use self.db_set() in on_update — Direct self.field = x is lost
  4. Use self.flags for recursion guards — Prevent circular hook triggers
  5. Isolate cleanup operations in on_cancel — Don't let one failure stop all
  6. Use frappe.db.escape() in permission queries — Prevent SQL injection
  7. Return explicit True/False from has_permission — None falls back to default
  8. Use frappe.log_error() for unexpected exceptions — Never swallow silently
  9. Use _() wrapper for all user-facing error messages — Enable translation

NEVER

  1. NEVER call self.save() in validate/on_update — Causes infinite recursion
  2. NEVER call frappe.db.commit() in controllers — Framework manages transactions
  3. NEVER put blocking validation in on_submit — Document already submitted
  4. NEVER skip super() in overridden methods — Breaks parent class logic
  5. NEVER return None from has_permission — Returns unpredictable results
  6. NEVER swallow exceptions with bare except: pass — Always log errors
  7. NEVER use override_doctype_class when extend_doctype_class works [v16+]
  8. NEVER put heavy operations in validate — Use frappe.enqueue() from on_update

Reference Files

FileContents
references/examples.mdReal controller error scenarios with diagnosis
references/anti-patterns.mdCommon controller mistakes with fixes
references/patterns.mdDefensive error handling patterns by lifecycle hook

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Frappe Errors Controllers AI 技能有什么作用?

Use when debugging or preventing errors in Frappe Document Controllers. Prevents autoname failures, validate loops, on_submit without is_submittable, wrong lifecycle hook choice, get_list permission errors, NestedSet errors, extend_doctype_class conflicts, missing super() calls, and recursion without flags. Covers error diagnosis by lifecycle phase for v14/v15/v16. Keywords: controller error, autoname, validate loop, on_submit, is_submittable,, save fails, validate error, on_submit not working, autoname broken, controller crash. get_list, NestedSet, extend_doctype_class, super, flags, recur...

为什么在 TypingMind 中使用 Frappe Errors Controllers?

因为您只需安装一次,就能搭配任何模型使用。Frappe Errors Controllers 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Frappe Errors Controllers?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package/tree/main/skills/source/errors/frappe-errors-controllers。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Frappe Errors Controllers?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Frappe Errors Controllers 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Frappe Errors Controllers 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Frappe Errors Controllers AI 技能免费吗?

是的。Impertio-Studio 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇