liveBook · Manning

Error code

As explained in Systems Programming with Zig

An error code is a value returned or stored to indicate that an operation failed and often identify the failure kind.

An error code is a value that reports whether an operation failed and can identify the kind of failure. Compared with a null pointer, a specific code offers better observability: it gives the caller a clue about what went wrong, at the cost of more boilerplate. section 5.4.1

For a C-facing Zig interface, an integer-backed enum can reserve zero for success and assign distinct values to failures. Catch Zig errors at the boundary and translate them into those codes, so the caller receives a C-friendly result. section 5.4.1

Listing 5.15 Failed recipes
const Success = enum (c_int) {
    ok = 0,
    out_of_memory = -1, #1
    nonexistent_recipe = -2, #1
};

const RecipeBookError = Allocator.Error || RecipeBook.GetRecipeError; #2

fn translateErr(e: RecipeBookError) Success { #3
    return switch (e) {
        error.OutOfMemory => .out_of_memory,
        error.NonexistentRecipe => .nonexistent_recipe,
    };
}

export fn wrapper_function() Success {
    recipeBookFunction() catch |e| return translateErr(e); #4
    return .ok;
}

This wrapper maps out-of-memory and nonexistent-recipe errors to distinct codes, returning ok when the operation succeeds. section 5.4.1

If the return value carries the status, where does the useful result go? An out parameter gives the caller a place to receive it. On success, the function writes the result through the pointer and returns ok; on failure, it returns an error code instead. section 5.4.1

Listing 5.16 Adding and deleting recipes
export fn recipe_create(
    book: *RecipeBook,
    name: [*:0]const u8,
    author: [*:0]const u8,
    instructions: [*:0]const u8,
    out_recipe_id: *RecipeId, #1
) Success {
    const ally = gpa.allocator();
    #2
    out_recipe_id.* = book.createRecipe(ally, .{
        .name = book.dupeCString(name) catch |e| return translateErr(e),
        .author = book.dupeCString(author) catch |e| return translateErr(e),
        .instructions = book.dupeCString(instructions) catch |e| {
            return translateErr(e);
        },
    }) catch |e| return translateErr(e);

    return .ok; #3
}

export fn recipe_delete(book: *RecipeBook, recipe_id: RecipeId) void { #4
    book.deleteRecipe(recipe_id);
}

Recipe creation writes the new ID through out_recipe_id and translates errors from string duplication or creation. section 5.4.1

Inside Zig, errors are values grouped into error sets. An error union combines a possible error with a successful payload; catch handles an error, while try propagates it. These language features make error codes more convenient without making failure disappear. section 3.2.2

Querying a GLFW error

After initialization, glfwGetError returns a previous error code, or zero if there is no error. An out parameter supplies a text description. A callback is another option when reporting errors matters more than handling each kind separately. section 7.3.2

Listing 7.4 Querying errors
var err_desc: [*c]const u8 = undefined; #1

_ = c.glfwInit(); #2
if (c.glfwGetError(&err_desc) != 0) { #3
    std.debug.print("init failed: {s}\n", .{err_desc}); #4
    return error.InitFailed; #4
}

The query checks for a nonzero code, prints the description, and returns a Zig error when initialization fails. section 7.3.2

How Systems Programming with Zig covers it

How deep it goes
Works through integer-backed codes, Zig error translation, and out parameters, then contrasts GLFW error queries and callbacks.
Examples
Uses recipe creation, checked Fibonacci input, and GLFW initialization to demonstrate different error-reporting paths.
What you can do after
Apply error-code translation in Zig when exposing operations to C callers, and inspect GLFW failures by query or callback.
How it connects
Connects error codes to error sets, error unions, foreign function interfaces, out parameters, and callbacks.

Also explained in

Compare how 3 books explain error code →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.