Skip to content

Reporting errors

Chung Leong edited this page Nov 17, 2026 · 3 revisions

Use Zig's standard error mechanism to trigger exceptions on the PHP side:

const php = @import("php/root.zig");

pub fn @"call factorial"(_: *@This(), args: struct {
    number: u64,
}) !u64 {
    var result: u64 = 1;
    for (1..args.number + 1) |i| {
        result, const overflow = @mulWithOverflow(result, i);
        if (overflow != 0) return error.TooLarge;
    }
    return result;
}
<?php

echo factorial(5), "\n";
echo factorial(100), "\n";
120
Exception: too large in /home/rwiggum/test.php:4
Stack trace:
#0 /home/rwiggum/test.php(4): factorial(100)
#1 {main}

Use failure.report() if you wish to provide detailed information concerning an error:

const std = @import("std");

const php = @import("php/root.zig");

pub fn @"call factorial"(_: *@This(), args: struct {
    number: u64,
}) !u64 {
    var result: u64 = 1;
    for (1..args.number + 1) |i| {
        result, const overflow = @mulWithOverflow(result, i);
        if (overflow != 0) return php.failure.report(
            "!{d} would result in a number larger than the maximum value of {}, which is {d}",
            .{ i, u64, std.math.maxInt(u64) },
        );
    }
    return result;
}
<?php

try {
    echo factorial(100), "\n";
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
!21 would result in a number larger than the maximum value of u64, which is 18446744073709551615

Clone this wiki locally