PHP 异常参数


PHP Exception Arguments

我正在开发一个PHP库,它可以被不同的PHP项目在各种环境中使用,我试图尽可能简约。

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

throw Exception('template has invalid tag');

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

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

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

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

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

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

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

例如,您在库中声明:

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
}

您可以定义自己的异常类,并在构造函数中添加变量。

例如:

class AnswerException extends 'Exception
{
    protected $group;
    public function __construct($message = "",  $group = null, $code = 0, 'Exception $previous = null){
        $this->group = $group;
        return parent::__construct($message, $code, $previous);
    }
    public function getGroup(){
        return $this->group;
    }
}

在这种情况下,可以使用以下语法引发异常:

throw new AnswerException('template has invalid tag',$tag);

然后稍后,您可以捕获AnswerException并使用$exception->getGroup()功能。

一种可能的解决方案是使用这样的sprintf

throw new Exception(sprintf(_('template has invalid tag %s'), $tag));

其中_()是您的本地化功能。

但这不是最好的解决方案,因为它仍然对 html 注入开放,并且当你有 5 个变量要传递时会变得非常混乱。 据我所知,WordPress使用这种本地化方法。