errors.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2012-2015 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. )
  11. func checkResponse(res *http.Response) error {
  12. // 200-299 and 404 are valid status codes
  13. if (res.StatusCode >= 200 && res.StatusCode <= 299) || res.StatusCode == http.StatusNotFound {
  14. return nil
  15. }
  16. if res.Body == nil {
  17. return fmt.Errorf("elastic: Error %d (%s)", res.StatusCode, http.StatusText(res.StatusCode))
  18. }
  19. slurp, err := ioutil.ReadAll(res.Body)
  20. if err != nil {
  21. return fmt.Errorf("elastic: Error %d (%s) when reading body: %v", res.StatusCode, http.StatusText(res.StatusCode), err)
  22. }
  23. errReply := new(Error)
  24. err = json.Unmarshal(slurp, errReply)
  25. if err == nil && errReply != nil {
  26. if errReply.Status == 0 {
  27. errReply.Status = res.StatusCode
  28. }
  29. return errReply
  30. }
  31. return nil
  32. }
  33. type Error struct {
  34. Status int `json:"status"`
  35. Message string `json:"error"`
  36. }
  37. func (e *Error) Error() string {
  38. if e.Message != "" {
  39. return fmt.Sprintf("elastic: Error %d (%s): %s", e.Status, http.StatusText(e.Status), e.Message)
  40. } else {
  41. return fmt.Sprintf("elastic: Error %d (%s)", e.Status, http.StatusText(e.Status))
  42. }
  43. }