Try using the pre_handle_404
hook instead:
add_filter( 'pre_handle_404', 'wpse_383506', 10, 2 );
function wpse_383506( $preempt, $wp_query ) {
if ( ! empty( $_GET['page_id'] ) &&
'342' === $_GET['page_id']
) {
// Throw a 404 error.
$wp_query->set_404();
// And prevent redirect to the page permalink (pretty URL).
remove_action( 'template_redirect', 'redirect_canonical' );
}
return $preempt; // always return it
}