Redirect a page id url but not the page slug

My client is asking me to force a 404 $ wp_query->set_404(); if the url is domain.com/page_id=342 but DON’t redirect if the url is domain.com/about even though they are the same page. I have to do this in the functions.php file and not .htaccess.

I have tried

add_action('init','add_get_val'); function add_get_val() {   if (isset($  _GET['page_id'])) {     $  param = $  _GET['page_id'];        if($  param == '342') {          global $  wp_query;            $  wp_query->set_404();            // status_header( 404 );            // get_template_part( 404 );             // exit();     }  }  } 

The code as it stands does not work. But if I uncomment the status_header, get_template…, and exit it does, however, it does not give the same 404 page.

What am I doing wrong?