wordpress plugin error handling

WordPress have WP_Error class for checking WordPress errors and error messages since version 2.1.0. WordPress use object of WP_Error class for reporting error from several WP function. However, we can use this object in plugin or theme to handle error within WordPress. This class containing verious useful method for managing error.

All methods

<?php
//Creating instance of error class
$error = new WP_Error( 'not_found', 'Page Not Found', 'Page Data' );

//Add new error to object
$error->add( 'not_match', 'Field Not Match' );

//Return all error codes from object
$data = $error->get_error_codes();
print_r( $data );
//Output: Array ( [0] => not_found [1] => not_match )

//Return first error code
echo $error->get_error_code();
//Output: not_found

//Return all error message
$data = $error->get_error_messages();
print_r( $data );
//Output: Array ( [0] => Page Not Found [1] => Field Not Match )

//Return error message by error code
$data = $error->get_error_messages( 'not_match' );
print_r( $data );
//Output: Array ( [0] => Field Not Match )

//Return first error message if no code are given
echo $error->get_error_message();
//Output: Page Not Found

//Return first error message for given error code
echo $error->get_error_message( 'not_match' );
//Output: Field Not Match

//Return first error data
echo $error->get_error_data();
//Output: Page Data

//Return error data from error code.
echo $error->get_error_data( 'not_found' );
//Output: Page Data

//add error data to error code
//syntex: add_data( $data, $code );
$error->add_data( 'Some data', 'not_match' );
echo $error->get_error_data( 'not_match' );
//Output: Some data

//Check whether variable is a WordPress Error.
//return bool True, if WP_Error. False, if not WP_Error.
$data = is_wp_error( $error );
var_dump( $data );
//Output: bool(true)

Source and hint: more background on this post

Leave a Comment