Logo de Error Handling

Error Handling

OrganizaçãoPopular
EpicenterHQ
error-handling

Use quando uma tarefa mencionar tratamento de erros, Wellcrafted Results, tipos de resultado, defineErrors, trySync, tryAsync, unwrap, exceções lançadas ou a decisão entre propagar, recuperar ou apresentar uma falha. Para registrar diagnósticos, use logging; para o ciclo de vida do cache, use query-layer.

Add to TypingMind

Visão geral

Publicado porEpicenterHQ
Repositórioepicenter
Nome da habilidadeerror-handling
Estrelas
4.8K
Forks
386
Arquivos incluídos
4
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 4

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por EpicenterHQ no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Error Handling no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/error-handling
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/EpicenterHQ/epicenter.git /tmp/epicenter
mkdir -p .claude/skills
cp -r /tmp/epicenter/.agents/skills/error-handling .claude/skills/error-handling
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Error Handling em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Error Handling automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Error Handling não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Error Handling

Epicenter uses Wellcrafted Results as its internal contract for ordinary failures. This skill owns the full path: define a tagged failure, adapt a throwing dependency, compose or recover from Results, then consume the outcome at the boundary that serves a person or another API. Use logging for diagnostics, query-layer for TanStack observation and cache behavior, and hono for HTTP response mechanics.

Source Of Truth

Ground every Wellcrafted behavior claim in the official wellcrafted-dev/wellcrafted source and tests. When maintaining this guidance, confirm that Epicenter's installed version matches the source being read. If it does not, report the version drift; dependency freshness is handled outside this skill. Treat other skills, examples, generated documentation, and DeepWiki as leads, not authority.

Read the scoped references only when needed:

Carry the outcome until a caller settles it

Fallible application work returns Result<T, E> while its caller can recover, add context, or choose how to present the outcome. Compose operations by handling or forwarding each possible Err. Preserve a lower error unless the current operation owns a meaningful new failure. An intentional fallback can return Ok, and a partial success may need success data that records what degraded, so the final caller can respond accurately.

The interaction owner consumes the final outcome into UI state, a toast, an HTTP response, or another host contract. That owner is determined by responsibility and lifetime, not by whether the code lives in an onclick attribute or an operations directory. A terminal action can return void or Promise<void> after settling the outcome. Infallible work stays plain, and unexpected bugs must not become routine Err values.

Do not treat every consumption boundary as an unwrap. Branch on the Result when the caller presents or recovers from an error. Use unwrap when the receiving API already communicates failure by throwing.

Choose The Contract First

Required contractPattern
Callee already returns Result<T, E>Inspect or forward its Err; do not wrap the call in trySync or tryAsync
Callee throws but caller needs Result<T, E>Adapt the throwing operation with trySync or tryAsync
Failure has a valid fallbackReturn Ok(fallback) from catch
Failure must propagate as dataReturn a typed defineErrors factory result from catch
Only known external failures should become ErrMap known exceptions and rethrow unknown ones
Surrounding API is exception-basedKeep its throwing contract
Cleanup must run on success, failure, cancellation, or early returnUse finally

Use trySync for a synchronous operation and tryAsync for an operation returning a Promise.

ts
const { data: response, error } = await tryAsync({
	try: () => fetch(url),
	catch: (cause) => RequestError.TransportFailed({ cause }),
});
if (error !== null) return Err(error);
return Ok(response);

defineErrors factories already return Err(...). Pass the raw cause into the factory and let the factory compose its message with extractErrorMessage. Do not use raw Err(cause) at a catch boundary: thrown values may be null or undefined, and an untyped cause loses the domain failure.

Cross a deliberate throwing boundary

Keep a Result as data while the caller can still recover, report, retry, or propagate. Use unwrap only where the surrounding API already throws as its failure channel:

ts
import { unwrap } from 'wellcrafted/result';

const document = unwrap(await openDocument(id));

unwrap returns Ok.data and throws Err.error. The throw is the boundary's contract, not a sign the failure was unexpected. Guard on error !== null instead when this function must recover, add context, or clean up.

A conceptual sketch is the one exception: unwrap may stand in for Result branches that do not change the behavior being explained. Say that the sketch throws on failure, and show the branch whenever a failure changes that behavior, such as keeping an unsaved draft after a save conflict.

Consume Every Possible Err Branch

  • If a value can be Result<T, E>, inspect or deliberately forward its error branch.
  • After destructuring, error is the raw E. Return Err(error), not error.
  • If you retained the whole Result, return it unchanged: if (result.error !== null) return result.
  • error !== null is the reliable discriminator. Never construct Err(null) or Err(undefined).
  • Data-only destructuring is correct when the catch branch always returns Ok<T> and the inferred type collapses to Ok<T>.
  • Error-only destructuring is correct when success data is irrelevant. The rule is to handle every possible Err, not to destructure fields you do not use.

Prefer an immediate guard so the success path stays linear.

When a caller translates every variant of a tagged error union, use an exhaustive switch (error.name) with default: error satisfies never. A guard for one variant followed by a shared path is different. See error variants for both shapes.

Own The Promise

tryAsync returns a Promise. Choose its owner explicitly:

  • await when this function inspects the Result.
  • return tryAsync(...) when the caller owns the Promise<Result<...>>.
  • Do not use bare void tryAsync(...): ordinary failures fulfill with Err, so a Promise rejection handler cannot observe them. A best-effort operation still needs an async owner that awaits the Result and explicitly logs or ignores its error branch.
  • In UI fire-and-forget code, attach presentation before discarding a Promise that fulfills with a Result: void save().then((result) => toastOnError(result, 'Save failed')). If the Promise can reject, adapt or catch that rejection first.

Keep Native Try-Catch When It Expresses The Contract

Traditional try-catch is appropriate when:

  • a finally block owns cleanup;
  • a generator must yield a failure rather than return a Result;
  • a framework boundary converts an exception directly into its required response shape;
  • code catches one known exception and rethrows everything else;
  • the surrounding public API intentionally throws.

Do not turn unknown programming errors into a generic domain failure. Mapping every throw to Err can hide bugs behind a misleading retryable error.

Final Check

  1. The function's throw-versus-Result contract is explicit.
  2. The wrapper covers one coherent failure meaning.
  3. Caught values become typed errors, intentional fallbacks, or selective rethrows.
  4. Every possible Err branch is handled, forwarded, logged, presented, or explicitly ignored by a named best-effort owner.
  5. Unknown bugs still reach the appropriate crash or framework error boundary.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Error Handling faz?

Use quando uma tarefa mencionar tratamento de erros, Wellcrafted Results, tipos de resultado, defineErrors, trySync, tryAsync, unwrap, exceções lançadas ou a decisão entre propagar, recuperar ou apresentar uma falha. Para registrar diagnósticos, use logging; para o ciclo de vida do cache, use query-layer.

Por que usar Error Handling no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Error Handling é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Error Handling no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/error-handling. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Error Handling?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Error Handling?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Error Handling com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Error Handling é gratuita?

A habilidade é publicada no GitHub por EpicenterHQ. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇