簡體   English   中英

如何使用JavaScript Elasticsearch客戶端錯誤?

[英]How to use the JavaScript Elasticsearch client errors?

我試圖解析來自通過nodeJs Express路由調用的Elasticsearch客戶端的錯誤。 我的情況是我想識別的超時錯誤。

我或多或少地實現了這樣的事情:

var client = new elasticsearch.Client( {
  host: process.env.ELASTICSEARCHLOCATION,
  requestTimeout:500,
  maxRetries:1
});

function returnResponse( response ) {
  return function ( resp ) {
    //stringExtract 
    if ( resp.hits && resp.hits.hits ) {
      response.status( 200 ).send( resp.hits.hits );
    }else{
      response.status( 200 ).send( [] );
    }
  };
}

function handleError( response ) {
  return function( err ){
    if ( err.statusCode == 404 ) {
      response.status( 200 ).send( [] );
    } else {
      console.error( err.message );
      response.status( err.statusCode ).send( err );
    }
  }
}
router.get( "/test", function ( req, res, next ) {
  log.data( "route GET: ", "/wynsureSearch/test" );
  log.request( req.url );

  client .search( {
    index: process.env.ELASTICSEARCHINDEX, //target the wynsure version aka the ES DB index
    type: [], //target the wynsure types
    body: req.body
  }).then( returnResponse( res ), handleError( res ) );
})   

沒有錯誤時,一切正常。 但是,當發生超時錯誤時, handleError()返回的函數中的斷點將向我顯示以下內容: 在此處輸入圖片說明

我從elastic.co錯誤文檔中讀取到存在標准錯誤。 如何使功能匹配文檔中的錯誤? 我希望能夠匹配例如RequestTimeout或InternalServerError。

在returnResponse和handleError中傳遞的res參數是在router.get( "/test", function ( req, res, next ) {傳遞的參數router.get( "/test", function ( req, res, next ) {因此它是undefined

來自Elasticsearch的報價

當回調傳遞給任何API方法時,將使用(錯誤,響應,狀態)進行調用。 如果您更喜歡使用Promise,請不要傳遞回調,否則將返回Promise。 承諾將通過響應主體來解決,或者因發生的錯誤而被拒絕(包括針對任何非“存在”方法的300多個響應)。

client .search( {
  index: process.env.ELASTICSEARCHINDEX, //target the wynsure version aka the ES DB index
  type: [], //target the wynsure types
  body: req.body }, function callback(err, response, status){
  if (err) {
    if(status == 404) res.status(200).send();
    else console.error(err.message);
  }
  else res.status(200).send(response); // res variable is refering to HTTP response whereas response is the result returned from elasticsearch.
 });

注意:ElasticSearch中的狀態碼具有其自身的含義,請不要將其與HTTP狀態碼混淆。

注意:Javascript支持封閉范圍,而不是塊范圍。

關於未定義的狀態代碼, ElasticSearch.JS中的狀態代碼定義似乎存在錯誤

@Spalger提供了有關如何使用JavaScript Elasticsearch客戶端錯誤的解決方案?:

// require the Error class
var EsClientRequestTimeout = require('elasticsearch').errors.RequestTimeout;

// ... somewhere else in your code

client.search(..., function (err) {
  if (err instanceof EsClientRequestTimeout) {
    console.log('timeout')
  } else {
    console.log('not a timeout')
  }
})

非常感謝@Spalger的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM