rest_format_combining_operation_error()
云策文档标注
概述
rest_format_combining_operation_error() 函数用于将组合操作错误格式化为 WP_Error 对象,适用于 WordPress REST API 开发中的错误处理。
关键要点
- 函数接受两个参数:$param(参数名)和 $error(错误详情数组)。
- 返回一个 WP_Error 对象,错误代码为 'rest_no_matching_schema'。
- 根据错误详情中是否包含 schema['title'],生成不同的错误消息。
- 错误消息支持国际化翻译,使用 __() 函数。
- 在 WP_Error 对象中可包含 'position' 数据,表示错误位置。
代码示例
function rest_format_combining_operation_error( $param, $error ) {
$position = $error['index'];
$reason = $error['error_object']->get_error_message();
if ( isset( $error['schema']['title'] ) ) {
$title = $error['schema']['title'];
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Schema title, 3: Reason. */
sprintf( __( '%1$s is not a valid %2$s. Reason: %3$s' ), $param, $title, $reason ),
array( 'position' => $position )
);
}
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Reason. */
sprintf( __( '%1$s does not match the expected format. Reason: %2$s' ), $param, $reason ),
array( 'position' => $position )
);
}注意事项
- 该函数自 WordPress 5.6.0 版本引入。
- 错误详情数组 $error 应包含 'index' 和 'error_object' 键,'error_object' 需有 get_error_message() 方法。
- 相关函数包括 rest_get_combining_operation_error(),用于获取组合操作错误。
原文内容
Formats a combining operation error into a WP_Error object.
Parameters
$paramstringrequired-
The parameter name.
$errorarrayrequired-
The error details.
Source
function rest_format_combining_operation_error( $param, $error ) {
$position = $error['index'];
$reason = $error['error_object']->get_error_message();
if ( isset( $error['schema']['title'] ) ) {
$title = $error['schema']['title'];
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Schema title, 3: Reason. */
sprintf( __( '%1$s is not a valid %2$s. Reason: %3$s' ), $param, $title, $reason ),
array( 'position' => $position )
);
}
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Reason. */
sprintf( __( '%1$s does not match the expected format. Reason: %2$s' ), $param, $reason ),
array( 'position' => $position )
);
}
Changelog
| Version | Description |
|---|---|
| 5.6.0 | Introduced. |