Примечание.
Второй пилот SDK в настоящее время находится в Technical Preview. Функциональность и доступность могут меняться.
`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 | булевый | Если это верно, не показывайте ошибку пользователю |
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)