6312
Ga
go-opencode-ai-zen-sdk / files
go-opencode-ai-zen-sdk / errors.go
1.0 KB
1package zen 2 3import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7) 8 9type APIError struct { 10 StatusCode int 11 RequestID string 12 Message string 13 Body []byte 14} 15 16func (e *APIError) Error() string { 17 if e.Message == "" { 18 return fmt.Sprintf("zen: request failed with status %d", e.StatusCode) 19 } 20 return fmt.Sprintf("zen: request failed with status %d: %s", e.StatusCode, e.Message) 21} 22 23type apiErrorEnvelope struct { 24 Error struct { 25 Message string `json:"message"` 26 Type string `json:"type"` 27 Code string `json:"code"` 28 } `json:"error"` 29 Message string `json:"message"` 30} 31 32func newAPIError(status int, header http.Header, body []byte) *APIError { 33 reqID := header.Get("x-request-id") 34 if reqID == "" { 35 reqID = header.Get("request-id") 36 } 37 38 msg := "" 39 var env apiErrorEnvelope 40 if err := json.Unmarshal(body, &env); err == nil { 41 if env.Error.Message != "" { 42 msg = env.Error.Message 43 } else if env.Message != "" { 44 msg = env.Message 45 } 46 } 47 48 return &APIError{ 49 StatusCode: status, 50 RequestID: reqID, 51 Message: msg, 52 Body: body, 53 } 54}