Skip to main content

오류 처리 후크

          `onErrorOccurred` 후크를 사용하여 사용자 지정 오류 로깅을 구현하고, 오류 패턴을 추적하고, 사용자에게 친숙한 오류 메시지를 코필로트 SDK제공합니다.

누가 이 기능을 사용할 수 있나요?

GitHub Copilot SDK 는 모든 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 참조하세요.

입력

분야유형설명
timestamp숫자오류가 발생한 시점의 Unix 타임스탬프
cwd문자열현재 작업 디렉터리
error문자열오류 메시지
errorContext문자열오류가 발생한 위치: "model_call", "tool_execution", "system"또는 "user_input"
recoverable부울오류를 복구할 수 있는지 여부

출력

기본 오류 처리를 위해 null를 반환하거나 undefined를 사용합니다. 그렇지 않으면 다음 필드 중 하나가 있는 객체를 반환합니다.

분야유형설명
suppressOutput부울true이면 사용자에게 오류 출력을 표시하지 마세요.
errorHandling문자열처리 방법: "retry", "skip"또는 "abort"
retryCount숫자다시 시도할 횟수(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)