gpt4 book ai didi

PHP 异常参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:57 25 4
gpt4 key购买 nike

我正在开发 PHP library ,不同的 PHP 项目可能会在各种环境中使用它,我正在努力做到尽可能简约。

例如,在某些情况下我必须抛出异常。

throw Exception('template has invalid tag');

如果没有标签的名称,这样的错误不是很有用:

throw Exception('template has invalid tag: '.$tag);

这将很难定位并可能导致各种注入(inject)问题。

问题:在 PHP 中使用异常传递额外变量的最佳方法是什么?

(注意:我的库执行 SQL 查询构建,我希望它专注于任务,而不是解决异常问题)

最佳答案

国际化不是您的图书馆的责任。为您的项目创建一个或多个 Exception 类(不建议抛出 \Exception,因为它太通用)并让它们将参数存储在属性中。

让错误消息保持原样,但也将值作为参数传递给新异常的构造函数。为他们提供 setter/getter 。错误消息是针对开发人员的。使用您的库的代码必须捕获异常并显示适合它们的错误消息。无论如何,它们不应显示您提供的原始消息。

例如,你在你的库中声明:

class InvalidTagException extends \Exception
{
protected $tag;

public function __construct($message, $tag, $code = 0, Throwable $previous = NULL)
{
// Let the parent class initialize its members
parent::__construct($message, $code, $previous);
// Initialize own members
$this->tag = $tag;
}

public function getTag()
{
return $tag;
}
}

// Declare other Exception classes in a similar fashion, for each kind of exception you throw
class InvalidValueException extends \Exception
{
// ...
}

使用您的库的应用程序:

try {
// call your library code here
} catch (InvalidTagException $e) {
// Handle in application specific way

} catch (InvalidValueException $e) {
// A different type of exception requires a different type of handling
}

关于PHP 异常参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com