WP_CLI::error()public staticWP-CLI 1.0

Outputs an error message prefixed with "Error:" to STDERR and terminates the process with exit code 1.

The message is always written to STDERR, so it can be correctly redirected separately from normal output.

By default the command will exit with code 1; if you need to continue execution, use the second argument false or WP_CLI::warning().

A specific exit code can be passed as the second argument. Or you can use WP_CLI::halt() for a controlled stop.

For non-fatal situations it is better to use WP_CLI::warning().

Method of the class: WP_CLI{}

No Hooks.

Returns

null. Returns nothing; used for logging an error and optionally terminating the process.

Usage

$result = WP_CLI::error( $message, $exit );
$message(string|WP_Error|Exception|Throwable) (required)

The error message or error object that will be written to STDERR with the prefix "Error:".

It accepts a string, a WP_Error object, or any Throwable. Useful for consistent output of fatal errors in custom WP‑CLI commands.

$exit(true|false|int)

Allows control over termination:

  • true — exit with code 1.
  • false — do not exit, just log the error and continue execution.
  • number ≥ 1 — exit with the specified code.

Default: true

Examples

1

#1 Demo

Exits with an error if the object cache could not be flushed.

if ( false === wp_cache_flush() ) {
	WP_CLI::error( 'The object cache could not be flushed.' );
}
1

#2 Explicit exit code

Terminates execution with the given code (for example, 3).

if ( $has_conflicts ) {
	WP_CLI::error( 'Conflicts detected. Aborting.', 3 );
}
0

#3 Passing a WP_Error and continuing execution

Logs the contents of a WP_Error and does not halt execution. However, for non-fatal cases WP_CLI::warning() is preferred.

$error = new WP_Error( 'invalid_data', 'Invalid payload received.' );

WP_CLI::error( $error, false );

// ... rest of the command code

WP_CLI::error() code WP-CLI 2.13.0-alpha

public static function error( $message, $exit = true ) {
	if ( null !== self::$logger && ! isset( self::get_runner()->assoc_args['completions'] ) ) {
		self::$logger->error( self::error_to_string( $message ) );
	}

	$return_code = false;
	if ( true === $exit ) {
		$return_code = 1;
	} elseif ( is_int( $exit ) && $exit >= 1 ) {
		$return_code = $exit;
	}

	if ( $return_code ) {
		if ( self::$capture_exit ) {
			throw new ExitException( '', $return_code );
		}
		exit( $return_code );
	}
}