REST API Error Log Under Tools
Records REST API requests that fail with a 4xx or 5xx status, with the route, method, user and error code, and lists the latest 100 under Tools > REST Errors for debugging integrations.
Opens WPIDE on
Code
// Keep this many entries.
$wpide_rest_log_size = 100;
// Log 404 responses too.
$wpide_rest_log_404 = true;
add_filter( 'rest_request_after_callbacks', function ( $response, $handler, $request ) use ( $wpide_rest_log_size, $wpide_rest_log_404 ) {
if ( is_wp_error( $response ) ) {
$data = $response->get_error_data();
$status = is_array( $data ) && isset( $data['status'] ) ? (int) $data['status'] : 500;
$code = $response->get_error_code();
} elseif ( $response instanceof WP_HTTP_Response ) {
$data = $response->get_data();
$status = $response->get_status();
$code = is_array( $data ) && isset( $data['code'] ) ? $data['code'] : '';
} else {
return $response;
}
if ( $status < 400 || ( 404 === $status && ! $wpide_rest_log_404 ) ) {
return $response;
}
$log = (array) get_option( 'wpide_rest_error_log', array() );
$log[] = array(
'time' => time(),
'method' => $request->get_method(),
'route' => $request->get_route(),
'status' => $status,
'code' => (string) $code,
'user' => get_current_user_id(),
);
update_option( 'wpide_rest_error_log', array_slice( $log, -$wpide_rest_log_size ), false );
return $response;
}, 10, 3 );
add_action( 'admin_menu', function () {
add_management_page( 'REST Errors', 'REST Errors', 'manage_options', 'wpide-rest-errors', function () {
$log = array_reverse( (array) get_option( 'wpide_rest_error_log', array() ) );
echo '<div class="wrap"><h1>REST API Errors</h1>';
if ( ! $log ) {
echo '<p>No errors recorded yet.</p></div>';
return;
}
echo '<table class="widefat striped"><thead><tr><th>When</th><th>Status</th><th>Method</th><th>Route</th><th>Code</th><th>User</th></tr></thead><tbody>';
foreach ( $log as $row ) {
$user = $row['user'] ? get_userdata( $row['user'] ) : false;
printf(
'<tr><td>%s</td><td>%d</td><td>%s</td><td><code>%s</code></td><td>%s</td><td>%s</td></tr>',
esc_html( wp_date( 'Y-m-d H:i:s', $row['time'] ) ),
(int) $row['status'],
esc_html( $row['method'] ),
esc_html( $row['route'] ),
esc_html( $row['code'] ),
esc_html( $user ? $user->user_login : 'visitor' )
);
}
echo '</tbody></table></div>';
} );
} );
Notes
Set $wpide_rest_log_404 to false to skip "not found" errors from bots; the log is stored in one non-autoloaded option.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.