You can encounter this error when upgrading from Drupal 8 to Drupal 9

Change

$entity = \Drupal::entityTypeManager()->getTranslationFromContext($entity);

to

$entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity);