c# - 在发出 HTTP POST 请求时捕获 ElasticSearch 异常
问题描述
我使用 ElasticSearch 7.2.0
。我使用System.Net.Http.HttpClient
该类向POST
我的 ElasticSearch 服务器发出请求:
private const string Host = "http://127.0.0.1";
private const int Port = 9200;
public static async Task<HttpResponseMessage> Receive(string jsonPostContents)
{
try
{
return await this.httpClient.PostAsync($"{Host}:{Port}/_bulk?pipeline=ParseDuration",
new StringContent(jsonPostContents, Encoding.UTF8, mediaType: MimeTypes.Json));
}
catch (Exception exception)
{
StringContent responseString = new StringContent($"Exception encountered: {exception.Message}.\n" +
$"Inner exception: {exception.InnerException?.Message}\n" +
$"Stack trace: {exception.StackTrace}");
return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = responseString };
}
}
在cmd.exe
我运行 ElasticSearch 的窗口中,将打印以下错误消息:
[2019-09-17T11:45:14,569][DEBUG][o.e.a.b.TransportBulkAction] [MyServer] failed to execute pipeline [ParseDuration] for document [testindex/_doc/5c91f6e0-b72f-48b2-8430-ad76a640347a]
java.lang.IllegalArgumentException: pipeline with id [ParseDuration] does not exist
at org.elasticsearch.ingest.IngestService$4.doRun(IngestService.java:408) [elasticsearch-7.2.0.jar:7.2.0]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:758) [elasticsearch-7.2.0.jar:7.2.0]
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37) [elasticsearch-7.2.0.jar:7.2.0]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at java.lang.Thread.run(Thread.java:835) [?:?]
Receive(string jsonPostContents)
但是,该方法不会返回 HTTP 错误响应,OK
而是返回响应(带有 HTTP 状态代码200
)。
如何确保可靠地捕获所有 ElasticSearch 异常?
解决方案
仅当存在连接问题时,批量 API 才会返回错误,否则返回 200。
您应该检查批量的响应。如果批量中有一个错误,响应将如下所示:
{
"took": x,
"errors": true,
"items":[
//element i: shows what happened with the item i from bulk
]
}
推荐阅读
- r - 从 ensembl_gene_id 获取 hgnc_symbol/gene_name
- python - 如何使用 python 提取 csv 文件的 '\r' 分隔字典
- javascript - 使用“.call”创建一个新的 JavaScript 对象而不是“new”
- java - 带有spring boot的apache cxf无法正常工作,但带有其他注释的spring boot可以正常工作?
- bash - 使用 bash 脚本对目录中的所有文件对执行程序
- python-3.x - Keras神经网络中的维度错误
- php - 从使用 file_get_contents 抓取的 HTML 表中提取数据
- java - 与阅读smali代码相反的替代方法?
- google-bigquery - 查询按城市获取每日负账户余额
- python - 从 Keras model.predict_generator 计算准确率