github.com/crosbymichael/octokat@v0.0.0-20160826194511-076a32289ed5/error.go (about) 1 package octokat 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "strings" 8 ) 9 10 type gitHubError struct { 11 Resource string `json:"resource"` 12 Field string `json:"field"` 13 Value interface{} `json:"value"` 14 Code string `json:"code"` 15 Message string `json:"message"` 16 } 17 18 type gitHubErrors struct { 19 Message string `json:"message"` 20 Errors []gitHubError `json:"errors"` 21 } 22 23 func handleErrors(body []byte) error { 24 var githubErrors gitHubErrors 25 err := json.Unmarshal(body, &githubErrors) 26 if err != nil { 27 return err 28 } 29 30 msg := buildErrorMessage(githubErrors) 31 32 return errors.New(msg) 33 } 34 35 func buildErrorMessage(githubErrors gitHubErrors) string { 36 errorMessages := make([]string, 0) 37 for _, e := range githubErrors.Errors { 38 var msg string 39 switch e.Code { 40 case "custom": 41 msg = e.Message 42 case "missing_field": 43 msg = fmt.Sprintf("Missing field: %s", e.Field) 44 case "invalid": 45 msg = fmt.Sprintf("Invalid value for %s: %v", e.Field, e.Value) 46 case "unauthorized": 47 msg = fmt.Sprintf("Not allow to change field %s", e.Field) 48 } 49 50 if msg != "" { 51 errorMessages = append(errorMessages, msg) 52 } 53 } 54 55 msg := strings.Join(errorMessages, "\n") 56 if msg == "" { 57 msg = githubErrors.Message 58 } 59 60 return msg 61 }