Skip to content

Errors API ​

Error types and handling utilities.

ValidationError ​

All possible validation errors:

ErrorMessageCode
TooShortvalue is too shortE001
TooLongvalue is too longE002
TooSmallvalue is too smallE003
TooLargevalue is too largeE004
InvalidEmailmust be a valid email addressE010
InvalidUrlmust be a valid URLE011
InvalidUuidmust be a valid UUIDE012
InvalidIpv4must be a valid IPv4 addressE013
InvalidIpv6must be a valid IPv6 addressE014
InvalidPhoneNumbermust be a valid phone numberE015
InvalidCreditCardmust be a valid credit card numberE016
MissingFieldfield is requiredE020
TypeMismatchwrong typeE021
PatternMismatchdoes not match required patternE022
MustBeLowercasemust be lowercaseE023
MustBeUppercasemust be uppercaseE024
WeakPasswordpassword is too weakE025
MustBeEvenmust be evenE030
MustBeOddmust be oddE031
NotMultiplemust be a multiple of the divisorE032
MustBeHttpsmust be HTTPSE033
OutOfRangevalue is out of rangeE034
NotInStepvalue must be in step incrementsE035
InvalidIntegermust be a valid integerE036
InvalidBooleanmust be a valid booleanE037
InvalidArraymust be a valid arrayE038
InvalidObjectmust be a valid objectE039
InvalidStringmust be a valid stringE040
UnknownFieldunknown fieldE041
DuplicateFieldduplicate fieldE042
InvalidDatemust be a valid ISO dateE043
InvalidTimemust be a valid ISO timeE044
LiteralMismatchdoes not match expected literalE045
NotInAllowedValuesvalue is not allowedE046
WrongLengthwrong lengthE047
TooFewItemstoo few itemsE050
TooManyItemstoo many itemsE051
DuplicateItemduplicate item foundE052
EmptyCollectioncollection cannot be emptyE053
NotPositivemust be positiveE054
NotNegativemust be negativeE055
NotZeromust not be zeroE056
DivisionByZerodivision by zeroE057
InvalidFormatinvalid formatE058
EmptyStringcannot be emptyE059
InvalidNumbermust be a valid numberE060
CustomValidationFailedvalidation failedE099
InvalidJsoninvalid JSON syntaxE100
NestedErrornested validation errorE101
ValidationFailedvalidation failedE102
ParseErrorfailed to parse valueE103

Error Functions ​

zig
const err = z.errors.ValidationError.TooShort;

z.errorMessage(err) // "value is too short"
z.errorCode(err)    // "E001"

FieldError ​

zig
pub const FieldError = struct {
    field: []const u8,      // Field path
    message: []const u8,    // Human message
    error_type: ValidationError,
    value: ?[]const u8,     // Actual value
    code: ?[]const u8,      // Error code
};

// Methods
err.format(allocator)  // "field: message (got: value)"
err.formatColored(allocator) // colored terminal output
err.toJson(allocator)  // {"field":"...","message":"..."}

ErrorList ​

zig
var errors = z.errors.ErrorList.init(allocator);
defer errors.deinit();

// Add errors
try errors.add("name", error.TooShort, "too short", "Jo");
try errors.addWithPath("user", "email", error.InvalidEmail, "invalid", null);
try errors.addIndexed("items", 2, error.TooLong, "too long", null);
try errors.addWithCode("field", error.TooShort, "msg", null, "E001");

// Limited collection
var limited = z.errors.ErrorList.initWithMax(allocator, 5);

// Check errors
errors.hasErrors()           // bool
errors.count()               // usize
errors.first()               // ?FieldError
errors.last()                // ?FieldError
errors.containsField("name") // bool
errors.containsErrorType(error.TooShort) // bool

// Format
errors.formatAll(allocator)  // "field: msg\nfield2: msg2\n"
errors.formatAllColored(allocator) // colorized terminal output
errors.formatAllWith(allocator, formatter) // custom messages
errors.formatAllColoredWith(allocator, formatter) // colored custom messages
errors.toJsonArray(allocator) // [{"field":"..."},...]

// Merge
try errors.merge(other_errors);

// Clear
errors.clear();

// Get errors for field
const field_errors = try errors.getErrorsForField("name", allocator);

JSON Parsing Errors ​

zig
var result = try z.fromJson(User, json, allocator);
defer result.deinit();

if (!result.isValid()) {
    for (result.error_list.errors.items) |err| {
        std.debug.print("[{s}] {s}: {s}\n", .{
            z.errorCode(err.error_type),
            err.field,
            err.message,
        });
    }

    // JSON output
    const json_errors = try result.error_list.toJsonArray(allocator);
    defer allocator.free(json_errors);
}

ValidationMessageConfig ​

Comptime config for overriding validation error messages on parameterized types:

zig
const config = errors.ValidationMessageConfig{
    .too_short = "custom too short message",
    .too_large = "custom too large message",
};

// Check if a message override exists
const msg = errors.messageForConfig(error.TooShort, config); // ?[]const u8

Available fields correspond to each ValidationError variant. Use via the f suffix types:

zig
const Name = Stringf(1, 50, .{ .too_short = "name is required" });

Or using the config directly:

zig
err.message = errors.messageForWithConfig(err_type, formatter, config);

Color Overrides ​

Override the default ANSI color for specific validation error types:

zig
// Set color overrides globally
z.setColorOverrides(.{
    .too_short = .bright_red,    // Override TooShort color
    .invalid_email = .magenta,   // Override InvalidEmail color
});

// Or set via Config
var cfg = z.getConfig();
cfg.color_overrides = .{
    .too_short = .bright_red,
    .weak_password = .yellow,
};
z.setConfig(cfg);

Color resolution order:

  1. ColorOverrides field for the error type (if non-null)
  2. Built-in default color from errorPresentation()

Disable colors entirely:

zig
z.disableColor();  // All output becomes plain text
z.enableColor();   // Re-enable colored output

Version Utilities ​

zig
z.getVersion()       // "0.0.3"
z.getVersionString() // "v0.0.3"
z.ISSUES_URL         // GitHub issues URL

Color Utilities ​

zig
const presentation = z.errorPresentation(z.errors.ValidationError.TooShort);
presentation.message // "value is too short"
presentation.code    // "E001"
presentation.color   // ANSI color used by the formatter

// The helper also exposes the color category directly.
z.errorColor(z.errors.ValidationError.InvalidEmail) // .blue

// Reusable formatter for custom messages
const custom = struct {
    fn format(err: z.errors.ValidationError) []const u8 {
        return switch (err) {
            z.errors.ValidationError.InvalidEmail => "please provide a valid email address",
            else => z.errorMessage(err),
        };
    }
}.format;

const custom_text = try errors.formatAllWith(allocator, custom);

Internal Error Reporting ​

WARNING

Use only for library bugs, NOT for validation errors!

zig
// Report unexpected internal error
z.reportInternalError("Unexpected null in parser");

// Report with error code
z.reportInternalErrorWithCode(error.OutOfMemory);

Output:

[ZIGANTIC ERROR] Unexpected null in parser

If you believe this is a bug in zigantic, please report it at:
  https://github.com/muhammad-fiaz/zigantic/issues

Update Checking ​

zig
// Disable automatic update checking (call before using library)
z.disableUpdateCheck();

// Or use custom config
z.setConfig(.{
    .auto_update_check = false,
    .show_update_notifications = false,
});

// Manual update check (background)
if (z.checkForUpdates(allocator)) |thread| {
    defer thread.join();
}

// Manual update check (synchronous)
var info = try z.checkForUpdatesSync(allocator);
defer info.deinit();
if (info.update_available) {
    std.debug.print("Update: {s}\n", .{info.latest_version});
}

Released under the MIT License.