承接 pmjones/throwable-properties 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

pmjones/throwable-properties

最新稳定版本:2.0.0

Composer 安装命令:

composer require pmjones/throwable-properties

包简介

Copies properties of a Throwable to a serializable object.

README 文档

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.

统计信息

  • 总下载量: 51.26k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 15
  • 点击次数: 1
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-10-20