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

Prompt selection helpers may also return:

ErrorDescription
InvalidConfigPrompt configuration is inconsistent
InvalidChoicePrompt answer did not match allowed choices
InvalidValuePrompt attempts exceeded without valid input
EndOfStreamInput stream ended before a valid answer

Strict include/exclude helpers may also return:

ErrorDescription
IncludeExcludeConflictSame value appeared in both include and exclude sets when conflict checks are enabled

Error Handling ​

Duplicate Option Behavior ​

Singleton options (for example standard store options and most typed helpers) now return DuplicateArgument when provided multiple times.

Repeatable actions such as count, append, extend, and callback_flag continue to allow multiple occurrences.

zig
const argv = [_][]const u8{ "--email", "a@example.com", "--email", "b@example.com" };
_ = parser.parse(&argv) catch |err| {
    if (err == error.DuplicateArgument) {
        std.debug.print("Error: duplicate argument\n", .{});
    }
    return;
};

Unknown Option Suggestions ​

In strict mode, unknown long options include a "Did you mean" suggestion when a close match exists.

Built-in command options (--help, --version) are also included in suggestion candidates.

Unknown subcommands also use closest-match suggestions when the command declares subcommands and no first positional argument is defined.

Suggestion behavior is configurable through Config:

  • suggest_closest
  • suggestion_max_distance
  • suggest_builtin_commands
  • suggest_subcommands
  • error_prefix
  • warning_prefix
  • unknown_option_hint
  • unknown_subcommand_hint
  • unknown_option_message
  • unknown_subcommand_message

For value errors, you can provide option-level customization with:

  • suggestion_hint (display a custom hint)
  • custom_error_message (override default validation message)

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.