pmjones / throwable-properties
将 Throwable 的属性复制到可序列化的对象中。
Requires
- php: ^8.1
Requires (Dev)
- pds/composer-script-names: ^1.0
- pds/skeleton: ^1.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^10.0
README
此包可以通过 Composer 安装,名称为 pmjones/throwable-properties。
composer require pmjones/throwable-properties ^2.0
当使用 json_encode()
与 Throwable 对象(如 Error 和 Exception)一起时,结果是空 JSON 对象。
try { // ... } catch (Throwable $e) { echo json_encode($e); // '{}' }
要将 Throwable 转换为适用于 json_encode()
的形式,请使用它实例化一个新的 ThrowableProperties
use pmjones\ThrowableProperties; try { // ... } catch (Throwable $e) { $t = new ThrowableProperties($e); echo json_encode($t); // '{"class": ... }' }
ThrowableProperties 实质上是一个由这些属性组成的数据传输对象
-
string $class
: Throwable 类。 -
string $message
: Throwable 消息。 -
string $string
: Throwable 的字符串表示形式。 -
int $code
: Throwable 代码。 -
string $file
: Throwable 被创建的文件名。 -
int $line
: Throwable 被创建的行号。 -
array $other
: Throwable 的所有其他属性(如果有)。 -
array $trace
: 移除了所有'args'
元素的堆栈跟踪数组。 -
?ThrowableProperties $previous
: 如果有的话,以前抛出的异常,以 ThrowableProperties 实例表示。
ThrowableProperties 可以转换为原始 Throwable 的字符串形式。
try { // ... } catch (Throwable $e) { $t = new ThrowableProperties($e); assert((string) $e === (string) $t)); }
如果您只想获取 ThrowableProperties 的值,可以调用 asArray()
try { // ... } catch (Throwable $e) { $t = new ThrowableProperties($e); $a = $t->asArray(); // do something with the array }
最后,您可以在自己的 Throwable jsonSerialize()
方法中使用 ThrowableProperty
use pmjones\ThrowableProperties; class MyException extends \Exception implements JsonSerializable { public function jsonSerialize() : mixed { return new ThrowableProperties($this); } }
可比较的库
Cees-Jan Kiewet 有一个类似的库,名为 php-json-throwable,使用函数来编码 Throwable 而不是独立的 DTO。它适用于 PHP 7.4 及更高版本,而此库仅适用于 PHP 8.1 及更高版本。
Eboreum 有一个相关包,名为 eboreum/exceptional。