Skip to content

Error Handling

Handle download errors gracefully.

Error Types

All download errors are in DownloadError:

Connection Errors

ErrorDescription
ConnectionFailedFailed to connect to server
ConnectionTimeoutConnection timed out
DnsResolutionFailedCould not resolve hostname
TlsErrorTLS/SSL error

Server Errors

ErrorDescription
ServerErrorServer returned error (4xx/5xx)
InvalidResponseMalformed response
TooManyRedirectsRedirect limit exceeded
InvalidBodyTruncated or invalid body

Resume Errors

ErrorDescription
ResumeNotSupportedServer doesn't support Range
FileModifiedFile changed since partial download
ContentLengthMissingContent-Length required

File Errors

ErrorDescription
FileOpenErrorCannot create/open file
FileWriteErrorCannot write to file
FileReadErrorCannot read file

Control Flow

ErrorDescription
RetriesExhaustedAll retry attempts failed
CancelledDownload cancelled by callback
OutOfMemoryMemory allocation failed

Basic Error Handling

zig
const result = client.download(url, output, null);

if (result) |bytes| {
    std.debug.print("Downloaded {d} bytes\n", .{bytes});
} else |err| {
    std.debug.print("Error: {s}\n", .{@errorName(err)});
}

Specific Error Handling

zig
client.download(url, output, null) catch |err| switch (err) {
    error.ConnectionFailed => {
        std.debug.print("Cannot connect. Check network.\n", .{});
    },
    error.ServerError => {
        std.debug.print("Server error. Try again later.\n", .{});
    },
    error.FileOpenError => {
        std.debug.print("Cannot write to output location.\n", .{});
    },
    error.RetriesExhausted => {
        std.debug.print("Download failed after retries.\n", .{});
    },
    else => {
        std.debug.print("Unexpected error: {s}\n", .{@errorName(err)});
    },
};

Error Messages

Get human-readable descriptions:

zig
const msg = downloader.errors_mod.getErrorMessage(err);
std.debug.print("{s}\n", .{msg});

Status Categories

Classify HTTP status codes:

zig
const category = downloader.StatusCategory.fromStatus(status);

switch (category) {
    .success => {},
    .redirect => {},
    .client_error => {},  // 4xx
    .server_error => {},  // 5xx
    else => {},
}

Retryable Check

Determine if an error is worth retrying:

zig
if (downloader.errors_mod.isRetryable(err)) {
    std.debug.print("Transient error, retry recommended\n", .{});
}

Next Steps

Released under the MIT License.