diff --git a/includes/Klasifai/Admin/SavePostHandler.php b/includes/Klasifai/Admin/SavePostHandler.php index 530a13487..49f04b072 100644 --- a/includes/Klasifai/Admin/SavePostHandler.php +++ b/includes/Klasifai/Admin/SavePostHandler.php @@ -17,6 +17,7 @@ class SavePostHandler { */ public function register() { add_action( 'save_post', [ $this, 'did_save_post' ] ); + add_action( 'admin_notices', [ $this, 'show_error_if' ] ); } /** @@ -68,7 +69,14 @@ function classify( $post_id ) { } $output = $classifier->classify_and_link( $post_id ); - //error_log( var_export( $output, true ) ); + + if ( is_wp_error( $output ) ) { + update_post_meta( $post_id, '_klasifai_error', [ + 'code' => $output->get_error_code(), + 'message' => $output->get_error_message(), + ] ); + } + return $output; } @@ -83,4 +91,44 @@ function get_classifier() { return $this->classifier; } + /** + * Outputs an Admin Notice with the error message if NLU + * classification had failed earlier. + */ + function show_error_if() { + global $post; + + if ( empty( $post ) ) { + return; + } + + $post_id = $post->ID; + + if ( empty( $post_id ) ) { + return; + } + + $error = get_post_meta( $post_id, '_klasifai_error', true ); + + if ( ! empty( $error ) ) { + delete_post_meta( $post_id, '_klasifai_error' ); + + $code = ! empty( $error['code'] ) ? $error['code'] : 500; + $message = ! empty( $error['message'] ) ? $error['message'] : 'Unknown NLU API error'; + + ?> +
+

+ Error: Failed to classify content with the IBM Watson NLU API. +

+

+ + - + +

+
+ $error ) { - \WP_CLI::log( $post_id . ': ' . $error->get_error_message() ); + \WP_CLI::log( $post_id . ': ' . $error->get_error_code() . ' - ' . $error->get_error_message() ); } } else { \WP_CLI::log( 'No posts to classify.' ); diff --git a/includes/Klasifai/Watson/APIRequest.php b/includes/Klasifai/Watson/APIRequest.php index 7f4ae2c5f..fd2318aaf 100644 --- a/includes/Klasifai/Watson/APIRequest.php +++ b/includes/Klasifai/Watson/APIRequest.php @@ -72,7 +72,11 @@ function get_result( $response ) { $json = json_decode( $body, true ); if ( json_last_error() === JSON_ERROR_NONE ) { - return $json; + if ( empty( $json['error'] ) ) { + return $json; + } else { + return new \WP_Error( $json['code'], $json['error'] ); + } } else { return new \WP_Error( 'Invalid JSON: ' . json_last_error_msg(), $body ); }