0

I am using the Drupal REST module. I have a custom module file I have created and it has a hook below

function magri_rest_user_presave($account) {


   if (isset($account->field_region->value)) {


        $taxonomy_query = \Drupal::entityQuery('taxonomy_term');
        $taxonomy_query ->condition('vid', "region")
            ->condition('name', $account->field_region->value);
        $tids = $taxonomy_query->execute();

        $tid = array_values($tids)[0];


        if($tid){
            //set taxonomy ref field on user entity
            $account->field_region_tax->target_id = $tid;

        }else{
            throw new NotFoundHttpException(t('Region not found!'));

        }
    }

The exception is thrown but it only gets printed in the logs:

Symfony\Component\HttpKernel\Exception\NotFoundHttpException: Region not found! in magri_rest_user_presave() (line 61 of /var/www/html/modules/custom/magri_rest/magri_rest.module).

Symfony\Component\HttpKernel\Exception\HttpException: Internal Server Error in Drupal\rest\Plugin\rest\resource\EntityResource->post() (line 198 of /var/www/html/core/modules/rest/src/Plugin/rest/resource/EntityResource.php).

I want something like below to be returned to the client:

{
    "error":"Region not found!", 
}
3
  • Have you tried throwing NotFoundException() class? – Ismail Cherri Sep 19 '19 at 16:49
  • I cant locate this class, can you kindly provide the fully qualified namespace? – tendaitakas Sep 20 '19 at 7:38
  • Sorry, my mistake, I had this class coming from another package I was using and saw something similar in Symfony docs, but it seems I was mistaken. – Ismail Cherri Sep 20 '19 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.