pmjones/throwable-properties

Copies properties of a Throwable to a serializable object.

2.0.0 2023-06-30 16:25 UTC

This package is auto-updated.

Last update: 2024-11-30 02:24:11 UTC


README

This package is installable via Composer as pmjones/throwable-properties.

composer require pmjones/throwable-properties ^2.0

When using json_encode() with Throwable objects, such as Error and Exception, the result is an empty JSON object.

try {
    // ...
} catch (Throwable $e) {
    echo json_encode($e); // '{}'
}

To convert a Throwable into a form suitable for json_encode(), instantiate a new ThrowableProperties with it:

use pmjones\ThrowableProperties;

try {
    // ...
} catch (Throwable $e) {
    $t = new ThrowableProperties($e);
    echo json_encode($t); // '{"class": ... }'
}

ThrowableProperties is essentially a Data Transfer Object composed of these properties:

  • string $class: The Throwable class.

  • string $message: The Throwable message.

  • string $string: A string representation of the Throwable.

  • int $code: The Throwable code.

  • string $file: The filename where the Throwable was created.

  • int $line: The line where the Throwable was created.

  • array $other: All other properties of the Throwable (if any).

  • array $trace: The stack trace array, with all 'args' elements removed.

  • ?ThrowableProperties $previous: The previously thrown exception, if any, represented as a ThrowableProperties instance.

ThrowableProperties is Stringable to the string form of the original Throwable.

try {
    // ...
} catch (Throwable $e) {
    $t = new ThrowableProperties($e);
    assert((string) $e === (string) $t));
}

If you just want the ThrowableProperties values, you can call asArray():

try {
    // ...
} catch (Throwable $e) {
    $t = new ThrowableProperties($e);
    $a = $t->asArray(); // do something with the array
}

Finally, you can use a ThrowableProperty inside your own Throwable jsonSerialize() methods:

use pmjones\ThrowableProperties;

class MyException extends \Exception implements JsonSerializable
{
    public function jsonSerialize() : mixed
    {
        return new ThrowableProperties($this);
    }
}

Comparable Libraries

Cees-Jan Kiewet has a comparable offering called php-json-throwable, using functions to encode a Throwable instead of a standalone DTO. It works on PHP 7.4 and later, whereas this library works only on PHP 8.1 and later.

Eboreum has a related package called eboreum/exceptional.