How To Get Error Message When Using WordPress HTTP API

404

One problem I’ve met when using WordPress HTTP API is that I couldn’t show the error message to users when the connection has failed. There are various problems of connection failure such as wrong URL, timeout, server block, etc. Users (and developers) need to see the error message to fix the PHP code or ask for support. But looking through the HTTP API Documentation, we see that there’s no entries for error message. All you can do (with the functions at the Codex) is getting the error code via wp_remote_retrieve_response_code(). You might say: that’s OK, I know the response code then I know the error message by looping an array of error codes. But what happens if you need to send many requests? Do you need to repeat the code of checking error code each time?

How To Get Error Message When Using WordPress HTTP API

Instead of that, WordPress provides us a better way to receive error message (not documented yet). When a request has failed, it presents itself an instance of WP_Error class. The WP_Error class has a method get_error_message() that receives the error message. So, the code to get error message will look like this:

$request = wp_remote_post( $url );
if ( is_wp_error( $request ) ) {
	// If the request has failed, show the error message
	echo $request->get_error_message();
} else {
	$content = wp_remote_retrieve_body( $request );
	// Do stuff with $content
}

2 thoughts on “How To Get Error Message When Using WordPress HTTP API

  1. There is handy is_wp_error() function that is better for check. Empty body does not necessarily mean request had failed and produced WP_Error response.

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Meta Box - Create advanced WordPress custom fields and custom meta boxes with ease Download Now