EntityMetadataWrapper: Be careful with empty / non-existing entities! (aka EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format.)

entity_metadata_wrapper() is an extremely helpful helper :)
Anyway today I found out something dangerous:

Be careful with constructs like this:

  1. $term = taxonomy_term_load($tid);
  2. $term_wrapper = entity_metadata_wrapper('taxonomy_term', $term);

IF the $term does NOT EXISTS here (for example not yet created), taxonomy_term_load() will return FALSE, which is absolutely correct!

Anyway entity_metadata_wrapper() can NOT handle this FALSE value which leads to mysterious Exceptions like:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set()...

later on!
So better check the $term value before you provide it to entity_metadata_wrapper:

  1. $term = taxonomy_term_load($tid);
  2. if ($term !== FALSE) {
  3.   $term_wrapper = entity_metadata_wrapper('taxonomy_term', $term);