Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Created July 24, 2012 22:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeschinkel/3173032 to your computer and use it in GitHub Desktop.
Save mikeschinkel/3173032 to your computer and use it in GitHub Desktop.
Potential method of using exceptions in WordPress
<?php
/**
* WordPress core would provide these...
*/
class WP_Exception extends Exception {
// Whatever special that would be needed goes here
}
class WP_Error {
function __construct($code = '', $message = '', $data = '') {
// Nothing different from existing WP_ Error class
}
}
function wp_remote_get( $url, $args ) {
$result = null;
/**
* More code above...
*
* This code is all a simulation showing throwing exceptions when requested
*/
if ( $could_not_connect && isset( $args['exceptions'] ) )
if ( true === $args['exceptions'] ) {
throw new WP_Exception( "Could not connect to {$url}",'http_request_failed' );
} else {
$exception_class = $args['exceptions'];
throw new $exception_class( "Could not connect to {$url}",'http_request_failed' );
}
else
return new WP_Error('http_request_failed',"Could not connect to {$url}" );
/**
* More code below...
*/
return $result;
}
/**
* Plugin developer would create this
*/
try {
$response = wp_remote_get( 'http://api.example.com/', array(
'exceptions' => true
));
$json = json_decode( $response['body'] );
echo $json['apidata']['messages']['latest'];
} catch ( WP_Exception $exception ) {
echo $exception->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment