2016-04-20 38 views
0

我目前正在開發使用elasticsearch的bash腳本,我需要一個很好的錯誤處理。 在這種情況下,我嘗試將文檔添加到elasticsearch並檢查操作是否成功。使用curl和elasticsearch處理錯誤

起初,我天真地想這:

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

但捲曲不會按照這種方式,仍然返回成功(0 - 這實際上是合乎邏輯的),即使JSON請求顯然是不正確(注意雙第3行逗號)和elasticsearch顯示錯誤。

所以答案不存在。現在我想我應該分析變量$ response來捕獲錯誤(grep?)。我發佈這個問題得到提示或解決方案,以可靠的方式做到這一點,並確保我不會錯過一個明顯的解決方案(也許捲曲選項,我不知道?)。

謝謝你的幫助!

其他有用的東西 $迴應的內容

Parsing JSON with Unix tools

例子:

成功:

{ 
    "_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: [email protected]f; 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: [email protected]f; line: 3, column: 17]", 
       "type": "json_parse_exception" 
      } 
     ], 
     "type": "mapper_parsing_exception" 
    }, 
    "status": 400 
} 
+0

嘗試通過在你的腳本行之後添加'回聲$'打印response'的'的狀態? – Inian

+0

我所說的「成功」和「失敗」都返回$ ?.這基本上是我用'&& echo ok ||嘗試的回聲失敗「,但是當我給elasticsearch一個不好的請求時,它不會捲曲失敗,這是elasticsearch。 – 021

+0

(由於某些原因無法編輯)我的意思是返回$?= 0(成功) – 021

回答

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 
+0

謝謝,這個選項正是我一直在尋找的! – 021