code: def htmlentityreplace_errors(ex):
      
      if isinstance(ex, UnicodeEncodeError):
          # Handle encoding errors
          bad_text = ex.object[ex.start:ex.end]
          text = _html_entities_escaper.escape(bad_text)
          return (compat.text_type(text), ex.end)
      raise ex
docs: An encoding error handler.
  
      This python `codecs`_ error handler replaces unencodable
      characters with HTML entities, or, if no HTML entity exists for
      the character, XML character references.
  
      >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace')
      'The cost was &euro;12.'