Created
July 24, 2012 22:14
-
-
Save mikeschinkel/3173032 to your computer and use it in GitHub Desktop.
Potential method of using exceptions in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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