WP_CLI::error_to_string()public staticWP-CLI 1.0

Convert a WP_Error or Exception into a string

Method of the class: WP_CLI{}

No Hooks.

Return

String.

Usage

$result = WP_CLI::error_to_string( $errors );
$errors(string|WP_Error|Exception|Throwable) (required)
-

WP_CLI::error_to_string() code WP-CLI 2.8.0-alpha

public static function error_to_string( $errors ) {
	if ( is_string( $errors ) ) {
		return $errors;
	}

	// Only json_encode() the data when it needs it
	$render_data = function( $data ) {
		if ( is_array( $data ) || is_object( $data ) ) {
			return json_encode( $data );
		}

		return '"' . $data . '"';
	};

	if ( $errors instanceof WP_Error ) {
		foreach ( $errors->get_error_messages() as $message ) {
			if ( $errors->get_error_data() ) {
				return $message . ' ' . $render_data( $errors->get_error_data() );
			}

			return $message;
		}
	}

	// PHP 7+: internal and user exceptions must implement Throwable interface.
	// PHP 5: internal and user exceptions must extend Exception class.
	if ( interface_exists( 'Throwable' ) && ( $errors instanceof Throwable ) || ( $errors instanceof Exception ) ) {
		return get_class( $errors ) . ': ' . $errors->getMessage();
	}

	throw new InvalidArgumentException(
		sprintf(
			"Unsupported argument type passed to WP_CLI::error_to_string(): '%s'",
			gettype( $errors )
		)
	);
}