Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion includes/Klasifai/Admin/SavePostHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' ] );
}

/**
Expand Down Expand Up @@ -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;
}

Expand All @@ -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';

?>
<div class="notice notice-error is-dismissible">
<p>
Error: Failed to classify content with the IBM Watson NLU API.
</p>
<p>
<?php echo esc_html( $code ); ?>
-
<?php echo esc_html( $message ); ?>
</p>
</div>
<?php
}
}

}
2 changes: 1 addition & 1 deletion includes/Klasifai/Command/KlasifaiCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public function post( $args = [], $opts = [] ) {
\WP_CLI::success( "Classified $total_success posts, $total_errors errors." );

foreach ( $errors as $post_id => $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.' );
Expand Down
6 changes: 5 additions & 1 deletion includes/Klasifai/Watson/APIRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
Expand Down