InvalidArgument
云策文档标注
概述
InvalidArgument 是 WordPress 中用于处理无效参数传递的异常类,继承自 InvalidArgumentException。它提供了一个静态方法 create 来生成标准化的异常消息。
关键要点
- InvalidArgument 类继承自 InvalidArgumentException,专门用于参数类型不匹配的异常处理。
- create 方法接受参数位置、名称、期望类型和实际类型,自动生成包含类名、函数名和详细信息的异常消息。
- 该方法利用 debug_backtrace 获取调用上下文,确保异常信息准确指向问题源头。
代码示例
public static function create($position, $name, $expected, $received) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s(): Argument #%d (%s) must be of type %s, %s given',
$stack[1]['class'],
$stack[1]['function'],
$position,
$name,
$expected,
$received
)
);
}
原文内容
Exception for an invalid argument passed.
Methods
| Name | Description |
|---|---|
| InvalidArgument::create | Create a new invalid argument exception with a standardized text. |
Source
final class InvalidArgument extends InvalidArgumentException {
/**
* Create a new invalid argument exception with a standardized text.
*
* @param int $position The argument position in the function signature. 1-based.
* @param string $name The argument name in the function signature.
* @param string $expected The argument type expected as a string.
* @param string $received The actual argument type received.
*
* @return WpOrgRequestsExceptionInvalidArgument
*/
public static function create($position, $name, $expected, $received) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s(): Argument #%d (%s) must be of type %s, %s given',
$stack[1]['class'],
$stack[1]['function'],
$position,
$name,
$expected,
$received
)
);
}
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |