package atlassian import ( "encoding/json" "errors" "fmt" "strings" ) // ErrResponseTooLarge is returned when a response body exceeds // Options.MaxResponseBytes. var ErrResponseTooLarge = errors.New("response body too large") // ErrNotJSON is returned when a successful response carries a body that // is not JSON -- typically an HTML login page from an SSO proxy in front // of the site. It is never silently treated as an empty object. var ErrNotJSON = errors.New("response is not JSON") // ErrTLSConfig marks a client that could not be built because its CA // file is unreadable or holds no certificate. var ErrTLSConfig = errors.New("TLS configuration") // ErrInvalidArgument marks a call rejected before any request was sent // (an empty key, an empty query, ...). var ErrInvalidArgument = errors.New("invalid argument") // APIError is a non-successful HTTP answer (after any retries). type APIError struct { StatusCode int Method string Path string // request path without query or host Body string // response body as received } func (e *APIError) Error() string { body := strings.TrimSpace(e.Body) if len(body) > 300 { body = body[:300] } return fmt.Sprintf("%s %s: HTTP %d: %s", e.Method, e.Path, e.StatusCode, body) } // Message extracts the human-readable message from Atlassian's error // bodies ({"errorMessages":[...]}, {"errors":{field:msg}}, // {"message":...}); for any other body it returns at most 500 bytes of // it, and a fixed text for an empty one. func (e *APIError) Message() string { body := []byte(e.Body) var parsed struct { ErrorMessages []string `json:"errorMessages"` Errors map[string]string `json:"errors"` Message string `json:"message"` } if err := json.Unmarshal(body, &parsed); err != nil { if len(body) == 0 { return "no additional detail from upstream" } if len(body) > 500 { body = body[:500] } return string(body) } if len(parsed.ErrorMessages) > 0 { return parsed.ErrorMessages[0] } if parsed.Message != "" { return parsed.Message } for field, msg := range parsed.Errors { return field + ": " + msg } return "no additional detail from upstream" } // StatusOf returns the HTTP status of an *APIError in err's chain, or 0. func StatusOf(err error) int { var apiErr *APIError if errors.As(err, &apiErr) { return apiErr.StatusCode } return 0 }