Use WordPress (built in) Error handling
Don't just return;
if some user input was wrong. Deliver them some information about was was done wrong.
function some_example_fn( $args = array() )
{
// If value was not set, build an error message
if ( ! isset( $args['some_value'] ) )
$error = new WP_Error( 'some_value', sprintf( __( 'You have forgotten to specify the %1$s for your function. %2$s Error triggered inside %3$s on line %4$s.', TEXTDOMAIN ), '$args[\'some_value\']', "\n", __FILE__, __LINE__ ) );
// die & print error message & code - for admins only!
if ( isset( $error ) && is_wp_error( $error ) && current_user_can( 'manage_options' ) )
wp_die( $error->get_error_code(), 'Theme Error: Missing Argument' );
// Elseif no error was triggered continue...
}
One error (object) for all
You can set up a global error object for your theme or plugin during the bootstrap:
function bootstrap_the_theme()
{
global $prefix_error, $prefix_theme_name;
// Take the theme name as error ID:
$theme_data = wp_get_theme();
$prefix_theme_name = $theme_data->Name;
$prefix_error = new WP_Error( $theme_data->Name );
include // whatever, etc...
}
add_action( 'after_setup_theme', 'bootstrap_the_theme' );
Later you can add unlimited Errors on demand:
function some_theme_fn( $args )
{
global $prefix_error, $prefix_theme_name;
$theme_data = wp_get_theme();
if ( ! $args['whatever'] && current_user_can( 'manage_options' ) ) // some required value not set
$prefix_error->add( $prefix_theme_name, sprintf( 'The function %1$s needs the argument %2$s set.', __FUNCTION__, '$args[\'whatever\']' ) );
// continue function...
}
Then you can fetch them all at the end of your theme. This way you don't interrupt rendering the page and can still output all your errors for developing
function dump_theme_errors()
{
global $prefix_error, $prefix_theme_name;
// Not an admin? OR: No error(s)?
if ( ! current_user_can( 'manage_options' ) ! is_wp_error( $prefix_error ) )
return;
$theme_errors = $prefix_error->get_error_messages( $prefix_theme_name );
echo '<h3>Theme Errors</h3>';
foreach ( $theme_errors as $error )
echo "{$error}\n";
}
add_action( 'shutdown', 'dump_theme_errors' );
You can find further information at this Q. A related ticket to fix the "working together" of WP_Error
and wp_die()
is linked from there and another ticket will follow. Comments, critics & such is appreciated.