Skip to content
This repository was archived by the owner on May 24, 2024. It is now read-only.

Commit d28274f

Browse files
authored
DA-4298: Add error handling in CreateDocument & UpdateDocument (#74)
* DA-4298 - add error handling in create & update function Signed-off-by: linonymous <[email protected]> * DA-4298 - fix error handling Signed-off-by: linonymous <[email protected]> * DA-4298 - Add http.StatusCreated Signed-off-by: linonymous <[email protected]>
1 parent 5285b50 commit d28274f

File tree

1 file changed

+52
-6
lines changed

1 file changed

+52
-6
lines changed

elastic/client.go

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -591,12 +591,35 @@ func (p *ClientProvider) CreateDocument(index, documentID string, body []byte) (
591591
}
592592
}()
593593

594-
resBytes, err := toBytes(res)
595-
if err != nil {
594+
if res.StatusCode == http.StatusOK || res.StatusCode == http.StatusCreated {
595+
var in interface{}
596+
if err = json.NewDecoder(res.Body).Decode(&in); err != nil {
597+
return nil, err
598+
}
599+
600+
bites, err := jsoniter.Marshal(in)
601+
if err != nil {
602+
return nil, err
603+
}
604+
return bites, nil
605+
}
606+
607+
if res.IsError() {
608+
if res.StatusCode == 404 {
609+
// index doesn't exist
610+
return nil, errors.New("index doesn't exist")
611+
}
612+
613+
var e map[string]interface{}
614+
if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
615+
return nil, err
616+
}
617+
618+
err = fmt.Errorf("[%s] %s: %s", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["reason"])
596619
return nil, err
597620
}
598621

599-
return resBytes, nil
622+
return nil, errors.New("create document failed")
600623
}
601624

602625
// UpdateDocumentByQuery ...
@@ -702,12 +725,35 @@ func (p *ClientProvider) UpdateDocument(index string, id string, body interface{
702725
}
703726
}()
704727

705-
resBytes, err := toBytes(res)
706-
if err != nil {
728+
if res.StatusCode == http.StatusOK {
729+
var in interface{}
730+
if err = json.NewDecoder(res.Body).Decode(&in); err != nil {
731+
return nil, err
732+
}
733+
734+
bites, err := jsoniter.Marshal(in)
735+
if err != nil {
736+
return nil, err
737+
}
738+
return bites, nil
739+
}
740+
741+
if res.IsError() {
742+
if res.StatusCode == 404 {
743+
// index doesn't exist
744+
return nil, errors.New("index doesn't exist")
745+
}
746+
747+
var e map[string]interface{}
748+
if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
749+
return nil, err
750+
}
751+
752+
err = fmt.Errorf("[%s] %s: %s", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["reason"])
707753
return nil, err
708754
}
709755

710-
return resBytes, nil
756+
return nil, errors.New("update document failed")
711757
}
712758

713759
// GetIndices get all indices based on a specific pattern , or you can use _all to get all indices

0 commit comments

Comments
 (0)