beter/exception-with-context

带有上下文的异常的接口、特质和类

1.0.1 2022-06-10 11:16 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:05:12 UTC


README

需求

PHP >= 7.4.0

安装

通过以下方式安装此扩展是首选方法: composer.

运行以下命令之一

composer require beter/exception-with-context

或将以下内容添加到您的 composer.json 文件的 require 部分。

"beter/exception-with-context": "~1.0.0"  // put the actual version

require

用法

ExceptionWithContext 的用法

use Beter\ExceptionWithContext\ExceptionWithContext;

$exceptionCode = 0;
$previousException = null;
$context = [
    'userIp' => '1.2.3.4',
    'userId' => 1,
    'request' => [
        'headers' => [ /* put headers data, for example */ ]
    ],
];

$e = new ExceptionWithContext('Action is not allowed for the user', $exceptionCode, $previousException, $context);

// or you may not to pass the context

$e = new ExceptionWithContext('Action is not allowed for the user', $exceptionCode, $previousException);

// or even skip $exceptionCode and $previousException

$e = new ExceptionWithContext('Action is not allowed for the user');

// or set context via setContext method call
$e = new ExceptionWithContext('Action is not allowed for the user');
$e->setContext($context);

// and get context back
var_dump($e->getContext());

您也可以创建异常链

use Beter\ExceptionWithContext\ExceptionWithContext;

try {
    do_smth();
} catch (\Throwable $catched) {
    $e = new ExceptionWithContext('Something went wrong', 0, $catched, ['key' => 'value']);
}

您可以重新定义您的基异常并向它们添加上下文特质。它们将具有相同的行为。

use Beter\ExceptionWithContext\ExceptionWithContextInterface;
use Beter\ExceptionWithContext\ExceptionWithContextTrait;

class CustomException extends \Exception implements ExceptionWithContextInterface
{
    use ExceptionWithContextTrait;

    public function __construct($message = "", $code = 0, Throwable $previous = null, array $context = [])
    {
        $this->context = $context;

        parent::__construct($message, $code, $previous);
    }
}

$e = new CustomException('Message text', 0, null, ['key' => 'value']);
$e->setContext(['newkey' => 'newvalue']);
var_dump($e->getContext());

此外,您还可以实现自己的自定义异常,甚至不需要使用特质。只需实现 Beter\Exception\ExceptionWithContextInterface 即可。

用法想法

  • 将上下文添加到日志消息中;
  • 通过在消息中直接使用占位符值来防止异常消息泛滥;
  • 向 sentry/logentries/datadog/newrelic 等传递更多信息。

您需要自行实现该支持。这里只有想法。

开发和测试

请参考 开发和测试文档.

相关项目

这些项目使用 beter/exception-with-context