Automattic\WooCommerce\StoreApi\Utilities

UnexpectedErrorResponse::create │ public static │ WC 11.3.0

Log an engine failure and create its Store API response.

Метод класса: UnexpectedErrorResponse{}

Хуков нет.

Возвращает

WP_Error.

Использование

$result = UnexpectedErrorResponse::create( $error, $failure_context, ?string $public_message ): WP_Error;
$error(Throwable) (обязательный)
Unexpected engine failure.
$failure_context(строка) (обязательный)
Context in which the failure occurred.
?string $public_message
.
По умолчанию: null

Список изменений

С версии 11.3.0 Введена.

Код UnexpectedErrorResponse::create() WC 11.3.0

public static function create( \Throwable $error, string $failure_context, ?string $public_message = null ): WP_Error {
	$log_message = sprintf(
		'Store API request failed in %1$s: %2$s: %3$s in %4$s:%5$d',
		$failure_context,
		get_class( $error ),
		$error->getMessage(),
		$error->getFile(),
		$error->getLine()
	);

	// PHP reports subclasses of ParseError and CompileError as E_ERROR, so match exact classes.
	$error_types = array(
		\ParseError::class   => E_PARSE,
		\CompileError::class => E_COMPILE_ERROR,
	);

	try {
		wc_get_logger()->critical(
			$log_message,
			array(
				'source'         => 'store-api',
				'error'          => array(
					'type' => $error_types[ get_class( $error ) ] ?? E_ERROR,
					'file' => $error->getFile(),
					'line' => $error->getLine(),
				),
				// Same shape the fatal-error shutdown handler logs, so log handlers and readers see one trace format.
				'backtrace'      => array_slice( explode( "\n", $error->getTraceAsString() ), 0, self::MAX_BACKTRACE_FRAMES ),
				// These failures reached remote logging as fatals before the dispatchers caught them.
				'remote-logging' => true,
			)
		);
	} catch ( \Throwable $logging_error ) {
		// Logging must not prevent the safe response, but a failure that also broke logging should not vanish.
		error_log( $log_message . ' (logging failed: ' . $logging_error->getMessage() . ')' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
	}

	$message = $public_message ?? __( 'Internal server error', 'woocommerce' );
	$data    = array( 'status' => 500 );

	if ( self::can_expose_details() ) {
		$message                 = $error->getMessage();
		$data['exception_class'] = get_class( $error );
	}

	return new WP_Error( 'woocommerce_rest_unknown_server_error', $message, $data );
}