123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package core
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "net/http"
- "strings"
- )
- type APIError struct {
- StatusCode int
- Header http.Header
- Body string
- Code string `json:"code"`
- Message string `json:"message"`
- Detail interface{} `json:"detail,omitempty"`
- }
- func (e *APIError) Error() string {
- var buf bytes.Buffer
- _, _ = fmt.Fprintf(&buf, "error http response:[StatusCode: %d Code: \"%s\"", e.StatusCode, e.Code)
- if e.Message != "" {
- _, _ = fmt.Fprintf(&buf, "\nMessage: %s", e.Message)
- }
- if e.Detail != nil {
- var detailBuf bytes.Buffer
- enc := json.NewEncoder(&detailBuf)
- enc.SetIndent("", " ")
- if err := enc.Encode(e.Detail); err == nil {
- _, _ = fmt.Fprint(&buf, "\nDetail:")
- _, _ = fmt.Fprintf(&buf, "\n%s", strings.TrimSpace(detailBuf.String()))
- }
- }
- if len(e.Header) > 0 {
- _, _ = fmt.Fprint(&buf, "\nHeader:")
- for key, value := range e.Header {
- _, _ = fmt.Fprintf(&buf, "\n - %v=%v", key, value)
- }
- }
- _, _ = fmt.Fprintf(&buf, "]")
- return buf.String()
- }
- func IsAPIError(err error, code string) bool {
- if ne, ok := err.(*APIError); ok {
- return ne.Code == code
- }
- return false
- }
|