函数文档

rest_convert_error_to_response()

💡 云策文档标注

概述

rest_convert_error_to_response() 函数用于将 WP_Error 实例转换为 WP_REST_Response 对象,以便在 REST API 中返回标准化的错误响应。它通过扁平化错误代码和消息,简化客户端处理。

关键要点

  • 函数接受一个必需的 WP_Error 参数,并返回一个 WP_REST_Response 对象。
  • 转换过程将错误数据整理为包含 code、message 和 data 键的关联数组列表,便于 JSON 序列化。
  • 支持处理多个错误,将主要错误放在 data 中,额外错误放在 additional_errors 键下。
  • 状态码从错误数据中提取,默认为 500。

代码示例

function rest_convert_error_to_response( $error ) {
    $status = array_reduce(
        $error->get_all_error_data(),
        static function ( $status, $error_data ) {
            return is_array( $error_data ) && isset( $error_data['status'] ) ? $error_data['status'] : $status;
        },
        500
    );

    $errors = array();

    foreach ( (array) $error->errors as $code => $messages ) {
        $all_data  = $error->get_all_error_data( $code );
        $last_data = array_pop( $all_data );

        foreach ( (array) $messages as $message ) {
            $formatted = array(
                'code'    => $code,
                'message' => $message,
                'data'    => $last_data,
            );

            if ( $all_data ) {
                $formatted['additional_data'] = $all_data;
            }

            $errors[] = $formatted;
        }
    }

    $data = $errors[0];
    if ( count( $errors ) > 1 ) {
        // Remove the primary error.
        array_shift( $errors );
        $data['additional_errors'] = $errors;
    }

    return new WP_REST_Response( $data, $status );
}

📄 原文内容

Converts an error to a response object.

Description

This iterates over all error codes and messages to change it into a flat array. This enables simpler client behavior, as it is represented as a list in JSON rather than an object/map.

Parameters

$errorWP_Errorrequired
WP_Error instance.

Return

WP_REST_Response List of associative arrays with code and message keys.

Source

function rest_convert_error_to_response( $error ) {
	$status = array_reduce(
		$error->get_all_error_data(),
		static function ( $status, $error_data ) {
			return is_array( $error_data ) && isset( $error_data['status'] ) ? $error_data['status'] : $status;
		},
		500
	);

	$errors = array();

	foreach ( (array) $error->errors as $code => $messages ) {
		$all_data  = $error->get_all_error_data( $code );
		$last_data = array_pop( $all_data );

		foreach ( (array) $messages as $message ) {
			$formatted = array(
				'code'    => $code,
				'message' => $message,
				'data'    => $last_data,
			);

			if ( $all_data ) {
				$formatted['additional_data'] = $all_data;
			}

			$errors[] = $formatted;
		}
	}

	$data = $errors[0];
	if ( count( $errors ) > 1 ) {
		// Remove the primary error.
		array_shift( $errors );
		$data['additional_errors'] = $errors;
	}

	return new WP_REST_Response( $data, $status );
}

Changelog

Version Description
5.7.0 Introduced.