Skip to content

Errors Reference ​

This document covers all error types in args.zig.

ParseError ​

Errors that occur during argument parsing:

ErrorDescription
UnknownOptionOption not defined in schema
MissingRequiredRequired argument not provided
MissingValueOption requires a value but none given
InvalidValueValue cannot be parsed as expected type
TooManyValuesMore values than nargs allows
TooFewValuesFewer values than nargs requires
InvalidChoiceValue not in allowed choices
ConflictingArgumentsMutually exclusive arguments used together
MissingDependencyRequired dependency argument not provided
DuplicateArgumentSame argument specified multiple times
InvalidFormatArgument format is malformed
UnexpectedPositionalPositional argument in unexpected position
UnknownSubcommandSubcommand not defined
MissingSubcommandRequired subcommand not provided
MutuallyExclusiveOptions that cannot be used together
OutOfMemoryMemory allocation failed
OverflowNumeric value too large
InvalidCharacterInvalid character in value

SchemaError ​

Errors that occur during schema definition:

ErrorDescription
DuplicateNameArgument name already used
DuplicateAliasShort/long option already used
InvalidConfigInvalid configuration value
PositionalAfterVariadicPositional after variable-length arg
RequiredAfterOptionalRequired positional after optional
InvalidNargsInvalid nargs specification
InvalidDefaultDefault value doesn't match type
InvalidChoicesChoices don't match value type
CircularDependencyDependency creates a cycle
SelfConflictArgument conflicts with itself

ValidationError ​

Errors that occur during value validation:

ErrorDescription
OutOfRangeValue outside allowed range
TooShortString shorter than minimum length
TooLongString longer than maximum length
PatternMismatchValue doesn't match required pattern
CustomValidationFailedCustom validator returned error
FileNotFoundPath doesn't exist
DirectoryNotFoundDirectory doesn't exist
PermissionDeniedInsufficient permissions
InvalidPathInvalid path format

Error Handling ​

Basic Error Handling ​

zig
var result = parser.parse(&args) catch |err| {
    switch (err) {
        error.MissingRequired => {
            std.debug.print("Error: Missing required argument\n", .{});
            try parser.printHelp();
        },
        error.UnknownOption => {
            std.debug.print("Error: Unknown option\n", .{});
        },
        else => {
            std.debug.print("Error: {any}\n", .{err});
        },
    }
    return;
};

Getting Error Messages ​

zig
const errors = @import("args").errors;

const message = errors.formatParseError(error.MissingRequired);
std.debug.print("{s}\n", .{message});
// Output: "missing required argument"

Error Context ​

zig
const ctx = errors.ErrorContext{
    .argument = "output",
    .message = "file not found",
    .value = "/invalid/path",
    .suggestion = "output.txt",
};

const formatted = try ctx.format(allocator);
defer allocator.free(formatted);
std.debug.print("{s}\n", .{formatted});
// Output: argument 'output': file not found (got '/invalid/path')
//         Did you mean 'output.txt'?

Suggestion System ​

args.zig includes a Levenshtein distance-based suggestion system:

zig
const candidates = [_][]const u8{ "verbose", "version", "help" };
const suggestion = errors.findClosestMatch("verbos", &candidates, 2);
// Returns: "verbose"

Exit on Error ​

By default, the parser exits on errors. Disable this for custom handling:

zig
var parser = try args.ArgumentParser.init(allocator, .{
    .name = "myapp",
    .config = .{ .exit_on_error = false },
});

Complete Example ​

zig
const std = @import("std");
const args = @import("args");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var parser = try args.ArgumentParser.init(allocator, .{
        .name = "myapp",
        .config = .{ .exit_on_error = false },
    });
    defer parser.deinit();

    try parser.addOption("output", .{ .short = 'o', .required = true });

    var result = parser.parseProcess() catch |err| {
        const msg = args.errors.formatParseError(err);
        std.debug.print("Error: {s}\n\n", .{msg});
        try parser.printHelp();
        std.process.exit(1);
    };
    defer result.deinit();

    // Process result...
}

Released under the MIT License.