Skip to content

Logging and error handling

Postgres error reporting functions provide log levels, formatting, and errors that can be thrown and caught like exceptions. pgzx wraps them for Zig.

Simple logging uses Log, Info, Notice or Warning:

elog.Info(@src(), "input_text: {s}\n", .{input_text});

The @src() built-in records the file location in the error report.

To report errors, use Error (returns a Zig error) or ErrorThrow (throws a Postgres error report):

if (target_char.len > 1) {
return elog.Error(@src(), "Target char is more than one byte", .{});
}

The module also exposes the C-style API (ereport, errcode, errmsg, …).

Postgres handles errors with longjmp, which can skip Zig defer/errdefer cleanup. pgzx provides a Zig alternative to PG_TRY:

var errctx = pgzx.err.Context.init();
defer errctx.deinit();
if (errctx.pg_try()) {
// Zig code that calls Postgres C functions.
} else {
return errctx.errorValue();
}

This catches errors raised by Postgres functions and returns them as Zig errors, so all defer/errdefer in the callers run. The wrap helper packages this pattern:

try pgzx.err.wrap(myFunction, .{arg1, arg2});

See pgzx.err.Context for details.