Observação
SDK do Copilot está atualmente em versão prévia técnica. A funcionalidade e a disponibilidade estão sujeitas a alterações.
O onErrorOccurred gancho é chamado quando ocorrem erros durante a execução da sessão. Use-o para:
- Implementar o log de erros personalizado
- Rastrear padrões de erro
- Fornecer mensagens de erro amigáveis ao usuário
- Disparar alertas para erros críticos
Assinatura de Hook
import type { ErrorOccurredHookInput, HookInvocation, ErrorOccurredHookOutput } from "@github/copilot-sdk";
type ErrorOccurredHandler = (
input: ErrorOccurredHookInput,
invocation: HookInvocation
) => Promise<
ErrorOccurredHookOutput | null | undefined
>;
Para obter assinaturas de hooks em Python, Go e .NET, consulte o github/copilot-sdk repositório.
Entrada
| Campo | Tipo | Descrição |
|---|---|---|
timestamp | número | Timestamp Unix quando o erro ocorreu |
cwd | cadeia | Diretório de trabalho atual |
error | cadeia | Mensagem de erro |
errorContext | cadeia | Onde o erro ocorreu: "model_call", , "tool_execution"ou "system"``"user_input" |
recoverable | boolean | Se o erro pode ser potencialmente recuperável |
Saída
Retorne null ou undefined para usar o tratamento de erros padrão. Caso contrário, retorne um objeto com qualquer um dos campos a seguir.
| Campo | Tipo | Descrição |
|---|---|---|
suppressOutput | boolean | Se for true, não mostre a saída de erro para o usuário |
errorHandling | cadeia | Como lidar com: "retry", "skip"ou "abort" |
retryCount | número | Número de vezes para repetir tentativa (se errorHandling for "retry") |
userNotification | cadeia | Mensagem personalizada para mostrar o usuário |
Exemplos
Log de erros básico
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;
},
},
});
Para obter exemplos em Python, Go e .NET, consulte o github/copilot-sdk repositório.
Enviar erros para o serviço de monitoramento
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;
},
},
});
Mensagens de erro amigáveis
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;
},
},
});
Suprimir erros não críticos
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;
},
},
});
Adicionar contexto de recuperação
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;
},
},
});
Rastrear padrões de erro
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;
},
},
});
Alerta sobre erros críticos
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;
},
},
});
Práticas recomendadas
-
**Sempre registre os erros.** Mesmo se você ocultá-los dos usuários, mantenha os registros para depuração. -
**Categorizar erros.** Use `errorContext` para lidar com erros diferentes adequadamente. -
**Não engole erros críticos.** Suprime apenas os erros que você tem certeza de que não são críticos. -
**Mantenha os ganchos fixos.** O tratamento de erros não deve atrasar a recuperação. -
**Monitorar padrões de erro.** Acompanhe erros recorrentes para identificar problemas sistêmicos.
Leitura adicional
-
[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)