0Pricing
Zig Academy · Aula

Encapsulando e relançando erros

Adicione contexto à medida que os erros sobem pela cadeia.

Encapsulando e relançando erros é uma aula grátis de Zig Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Zig Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Zig Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Errors Travel Upward

When a function cannot handle a failure itself, it passes the error to its caller. Along the way you can adjust or re-throw it.

Re-throw with try

The simplest re-throw is try. It forwards the original error unchanged to your caller, so the same value keeps bubbling up.

const data = try readFile(path);

Catch Then Return

To translate an error, catch it and return a different one. This swaps a low-level error for one that fits your own API.

const f = open(path) catch return error.ConfigMissing;

Map Errors with switch

Combine catch with a switch to map each underlying error to a clearer one, while passing the rest through unchanged.

parse(s) catch |e| switch (e) {
    error.Empty => return error.NoInput,
    else => return e,
};

Zig Has No Stack Traces by Value

An error in Zig is just a tag, not an object holding context. To add detail you re-throw a more descriptive error of your own.

Attach Context Separately

Since the error tag carries no message, log the details where the failure happens, then return the higher-level error to the caller.

open(path) catch |e| {
    std.log.err("open {s}: {}", .{ path, e });
    return error.LoadFailed;
};

Widen the Error Set

If you return a new error, your function's error set must include it. An inferred !T set grows to cover everything you return.

fn load() !Config {
    return open(".cfg") catch error.LoadFailed;
}

Preserve or Replace

Decide per layer: forward the exact error with try, or replace it with one that makes more sense to your caller. Both are valid.

Keep Boundaries Clean

At a module boundary, map internal errors to a small public set. Callers then depend on stable names, not your internals.

Pair with errdefer

When you re-throw, any errdefer in scope still fires first. So you can rollback resources and translate the error in one path.

Meaningful Failures

Wrapping errors turns a raw cause into a message that fits your domain. The caller sees a clear error instead of an internal detail.

Quick Check

You want to replace a low-level error.NotFound with your own error.ConfigMissing for the caller. Which works?

Recap

You re-threw errors with try, mapped them via catch and switch, logged context, and widened error sets to keep failures meaningful. ✅

Perguntas Frequentes

A aula “Encapsulando e relançando erros” é grátis?

Sim — o texto completo de “Encapsulando e relançando erros” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Zig Academy, atualize para CoddyKit PRO. O curso de Zig Academy inclui 4 aulas no total.

O que vou aprender em “Encapsulando e relançando erros”?

Adicione contexto à medida que os erros sobem pela cadeia. Você pratica Zig Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Zig Academy?

Nenhuma experiência prévia é necessária. Zig Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Encapsulando e relançando erros”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Zig Academy?

Sim. Cada aula de Zig Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Recuperando-se com catch
  2. Selecionando erros específicos
  3. errdefer para limpeza após falhas
  4. Encapsulando e relançando erros
← Voltar para Zig Academy