使用curl和elasticsearch处理错误

问题描述 投票:0回答:1

我目前正在开发使用elasticsearch的bash脚本,我需要一个很好的错误处理。在这种情况下,我尝试将文档添加到elasticsearch并检查操作是否成功。

起初我天真地试过这个:

response=$(curl -XPOST 'http://localhost:9200/indexation/document' -d '
{
  "content":"'"$txt"'",,
  "date_treatment":"'"$(date +%Y-%m-%d)"'"
}') && echo ok || echo fail

但是curl不会以这种方式工作并仍然返回成功(0 - 这实际上是逻辑的),即使json请求明显不正确(注意第3行的双逗号)并且elasticsearch显示错误。

所以答案不存在。现在我想我应该分析变量$ response来捕获错误(grep?)。我发布这个问题,以便以可靠的方式获得提示或解决方案,并确保我没有错过一个明显的解决方案(可能是我不知道的卷曲选项?)。

其他有用的东西

Parsing JSON with Unix tools

$ response的内容示例:

成功:

{
    "_id": "AVQz7Fg0nF90YvJIX_2C",
    "_index": "indexation",
    "_shards": {
        "failed": 0,
        "successful": 1,
        "total": 1
    },
    "_type": "document",
    "_version": 1,
    "created": true
}

错误:

{
    "error": {
        "caused_by": {
            "reason": "json_parse_exception: Unexpected character (',' (code 44)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name\n at [Source: org.elasticsearch.common.io.stream.InputStreamStreamInput@139163f; line: 3, column: 17]",
            "type": "json_parse_exception"
        },
        "reason": "failed to parse",
        "root_cause": [
            {
                "reason": "json_parse_exception: Unexpected character (',' (code 44)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name\n at [Source: org.elasticsearch.common.io.stream.InputStreamStreamInput@139163f; line: 3, column: 17]",
                "type": "json_parse_exception"
            }
        ],
        "type": "mapper_parsing_exception"
    },
    "status": 400
}
bash http curl elasticsearch error-handling
1个回答
2
投票

一个简单的解决方法是使用-f/--fail选项。

根据documentation

(HTTP)服务器错误无提示失败(根本没有输出)。这主要是为了更好地启用脚本等以更好地处理失败的尝试。在正常情况下,当HTTP服务器无法传递文档时,它会返回一个HTML文档(通常也会描述原因和更多)。该标志将阻止卷曲输出并返回错误22。

该方法不是故障安全的,并且存在非成功响应代码将会漏掉的情况,尤其是涉及认证时(响应代码401和407)。

例:

response=$(curl -XPOST 'http://localhost:9200/indexation/document' -d '
{
  "content":"'"$txt"'",,
  "date_treatment":"'"$(date +%Y-%m-%d)"'"
}' -f ) && echo ok || echo fail
© www.soinside.com 2019 - 2024. All rights reserved.