Skip to main content

错误处理挂钩

使用 onErrorOccurred 挂钩实现自定义错误日志记录、跟踪错误模式,并在中 Copilot SDK提供用户友好的错误消息。

谁可以使用此功能?

GitHub Copilot SDK 适用于所有 Copilot 计划。

在本文中

注意

Copilot SDK 当前处于 技术预览版. 功能和可用性可能会发生更改。

当会话执行期间发生错误时调用 onErrorOccurred 钩子函数。 使用它可执行以下操作:

  • 实现自定义错误日志记录
  • 跟踪错误模式
  • 提供用户友好的错误消息
  • 触发关键错误的警报

挂钩签名

import type { ErrorOccurredHookInput, HookInvocation, ErrorOccurredHookOutput } from "@github/copilot-sdk";
type ErrorOccurredHandler = (
  input: ErrorOccurredHookInput,
  invocation: HookInvocation
) => Promise<
  ErrorOccurredHookOutput | null | undefined
>;

有关 Python、Go 和 .NET 中的挂钩签名,请参阅 github/copilot-sdk 存储库

输入

领域类型说明
timestampnumber发生错误的 Unix 时间戳
cwd字符串当前工作目录
error字符串错误消息
errorContext字符串发生错误的位置:"model_call"、、"tool_execution"``"system""user_input"
recoverable布尔是否可以可能从错误中恢复

输出

返回 nullundefined 以使用默认错误处理。 否则,返回具有以下任何字段的对象。

领域类型说明
suppressOutput布尔如果为 true,则不向用户显示错误输出
errorHandling字符串如何处理:"retry""skip""abort"
retryCountnumber重试次数(如果 errorHandling"retry"
userNotification字符串显示给用户的自定义消息

示例

基本错误日志记录

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (
      input, invocation
    ) => {
      console.error(
        `[${invocation.sessionId}] `
        + `Error: ${input.error}`
      );
      console.error(
        `  Context: ${input.errorContext}`
      );
      console.error(
        `  Recoverable: ${input.recoverable}`
      );
      return null;
    },
  },
});

有关 Python、Go 和 .NET 中的示例,请参阅 github/copilot-sdk 存储库

将错误发送到监控服务

import { captureException } from "@sentry/node"; // or your monitoring service

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input, invocation) => {
      captureException(new Error(input.error), {
        tags: {
          sessionId: invocation.sessionId,
          errorContext: input.errorContext,
        },
        extra: {
          error: input.error,
          recoverable: input.recoverable,
          cwd: input.cwd,
        },
      });
      
      return null;
    },
  },
});

用户友好型错误消息

const ERROR_MESSAGES: Record<string, string> = {
  "model_call":
    "There was an issue communicating "
    + "with the AI model. Please try again.",
  "tool_execution":
    "A tool failed to execute. "
    + "Please check your inputs and try again.",
  "system":
    "A system error occurred. "
    + "Please try again later.",
  "user_input":
    "There was an issue with your input. "
    + "Please check and try again.",
};

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input) => {
      const friendlyMessage =
        ERROR_MESSAGES[input.errorContext];

      if (friendlyMessage) {
        return {
          userNotification: friendlyMessage,
        };
      }

      return null;
    },
  },
});

抑制非关键错误

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input) => {
      // Suppress tool execution errors
      // that are recoverable
      if (
        input.errorContext === "tool_execution"
        && input.recoverable
      ) {
        console.log(
          `Suppressed recoverable error: `
          + `${input.error}`
        );
        return { suppressOutput: true };
      }
      return null;
    },
  },
});

添加恢复上下文

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input) => {
      if (
        input.errorContext === "tool_execution"
      ) {
        return {
          userNotification:
            "The tool failed. Here are some "
            + "recovery suggestions:\n"
            + "- Check if required dependencies "
            + "are installed\n"
            + "- Verify file paths are correct\n"
            + "- Try a simpler approach",
        };
      }

      if (
        input.errorContext === "model_call"
        && input.error.includes("rate")
      ) {
        return {
          errorHandling: "retry",
          retryCount: 3,
          userNotification:
            "Rate limit hit. Retrying...",
        };
      }

      return null;
    },
  },
});

跟踪错误模式

interface ErrorStats {
  count: number;
  lastOccurred: number;
  contexts: string[];
}

const errorStats =
  new Map<string, ErrorStats>();

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (
      input, invocation
    ) => {
      const key =
        `${input.errorContext}:`
        + `${input.error.substring(0, 50)}`;

      const existing =
        errorStats.get(key) || {
          count: 0,
          lastOccurred: 0,
          contexts: [],
        };

      existing.count++;
      existing.lastOccurred = input.timestamp;
      existing.contexts.push(
        invocation.sessionId
      );

      errorStats.set(key, existing);

      // Alert if error is recurring
      if (existing.count >= 5) {
        console.warn(
          `Recurring error detected: `
          + `${key} (${existing.count} times)`
        );
      }

      return null;
    },
  },
});

针对严重错误发出警报

const CRITICAL_CONTEXTS = [
  "system", "model_call",
];

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (
      input, invocation
    ) => {
      if (
        CRITICAL_CONTEXTS.includes(
          input.errorContext
        )
        && !input.recoverable
      ) {
        await sendAlert({
          level: "critical",
          message:
            `Critical error in session `
            + `${invocation.sessionId}`,
          error: input.error,
          context: input.errorContext,
          timestamp: new Date(
            input.timestamp
          ).toISOString(),
        });
      }

      return null;
    },
  },
});

最佳做法

  •         **始终记录错误。** 即使对用户隐藏它们,也要保留日志以供调试。
    
  •         **对错误进行分类。** 使用 `errorContext` 适当处理不同的错误。
    
  •         **不要忽略关键错误。** 仅忽略那些你确定是非关键的错误。
    
  •         **保持挂钩紧固。** 错误处理不应减慢恢复速度。
    
  •         **监测错误模式。** 跟踪定期错误以识别系统性问题。
    

延伸阅读

  •         [AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/quickstart)
    
  •         [AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/session-lifecycle)
    
  •         [AUTOTITLE](/copilot/how-tos/copilot-sdk/use-hooks/pre-tool-use)