Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active October 14, 2016 22:30
Show Gist options
  • Select an option

  • Save igorbenic/6c2df64e38187b0addbcfb440a2a5151 to your computer and use it in GitHub Desktop.

Select an option

Save igorbenic/6c2df64e38187b0addbcfb440a2a5151 to your computer and use it in GitHub Desktop.
How to Handle WordPress Errors with WP_Error Class | http://www.ibenic.com/how-to-handle-wordpress-errors-with-wp_error-class
<?php
$error_code = 'my_error_code';
$error_message = __( 'My Error Message', 'my_textdomain' );
$api_error = new WP_Error( $error_code, $error_message );
<?php
$response_from_paypal = paypal_retrieve_approaval_link();
// We have an error
if( $response_from_paypal['ACK'] != 'SUCCESS' ) {
$error_code = $response_from_paypal['L_ERRORCODE0'];
$error_short_message = $response_from_paypal['L_SHORTMESSAGE0'];
$error_long_message = $response_from_paypal['L_LONGMESSAGE0'];
$api_error = new WP_Error( $error_code, $error_short_message ); // We have added a short message, it will be the first code
// Let's add a long message with description
$api_error->add( $error_code, $error_long_message );
}
<?php
// ...
$retrieved_error_from_plugin = did_paypal_pay();
// It is a WordPress Error
if( is_wp_error( $retrieved_error_from_plugin ) ) {
$retrieved_error_from_plugin->get_error_codes();
/*
array(
'10002'
);
*/
$retrieved_error_from_plugin->get_error_code();
/*
'10002'
*/
$retrieved_error_from_plugin->get_error_messages( '10002' );
$retrieved_error_from_plugin->get_error_message( '10002' );
/* Same:
array(
'Authentication/Authorization Failed',
'Account is locked or inactive'
);
*/
$retrieved_error_from_plugin->get_error_messages( '10005' );
/*
array() // Empty
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment