代码之家  ›  专栏  ›  技术社区  ›  user2896120

无法捕获ElasticSearch连接错误

  •  0
  • user2896120  · 技术社区  · 5 年前

    我有一个模型是这样的:

    class Topic(models.Model):
        name = models.CharField(max_length=50, unique=True)
    
        def indexing(self):
        try:
            connections.create_connection()
    
            obj = TopicIndex(
                meta={'id': self.id},
                name=self.name,
            )
            obj.save()
            return obj.to_dict(include_meta=True)
    
        except ConnectionError:
            raise ValidationError("Something is wrong.")
    

    每当保存新主题时,它也会将其保存到ElasticSearch中。但是,假设ElasticSearch已关闭。如果我保存了一个新主题,我将开始出现如下错误:

    elasticsearch.exceptions.ConnectionError错误: 无法建立连接,因为目标计算机主动拒绝 (信息技术)

    这个错误是有道理的,但是,我从来没有抓住它。”“有点不对劲”永远不会被展示出来。相反,一次又一次地尝试建立连接。

    1 回复  |  直到 5 年前
        1
  •  1
  •   JPG    5 年前

    你得赶上火车 elasticsearch 的异常类为,

    from elasticsearch.exceptions import ConnectionError as ElasticConnectionError
    
    
    class Topic(models.Model):
        name = models.CharField(max_length=50, unique=True)
    
        def indexing(self):
            try:
                # your try clause
            except ElasticConnectionError:
                raise ValidationError("Something is wrong.")

    ConnectionError 例外