forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
86 lines (71 loc) · 1.82 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package openai
import (
"encoding/json"
"fmt"
)
// APIError provides error information returned by the OpenAI API.
type APIError struct {
Code any `json:"code,omitempty"`
Message string `json:"message"`
Param *string `json:"param,omitempty"`
Type string `json:"type"`
HTTPStatusCode int `json:"-"`
}
// RequestError provides informations about generic request errors.
type RequestError struct {
HTTPStatusCode int
Err error
}
type ErrorResponse struct {
Error *APIError `json:"error,omitempty"`
}
func (e *APIError) Error() string {
if e.HTTPStatusCode > 0 {
return fmt.Sprintf("error, status code: %d, message: %s", e.HTTPStatusCode, e.Message)
}
return e.Message
}
func (e *APIError) UnmarshalJSON(data []byte) (err error) {
var rawMap map[string]json.RawMessage
err = json.Unmarshal(data, &rawMap)
if err != nil {
return
}
err = json.Unmarshal(rawMap["message"], &e.Message)
if err != nil {
return
}
// optional fields for azure openai
// refs: https://github.com/sashabaranov/go-openai/issues/343
if _, ok := rawMap["type"]; ok {
err = json.Unmarshal(rawMap["type"], &e.Type)
if err != nil {
return
}
}
// optional fields
if _, ok := rawMap["param"]; ok {
err = json.Unmarshal(rawMap["param"], &e.Param)
if err != nil {
return
}
}
if _, ok := rawMap["code"]; !ok {
return nil
}
// if the api returned a number, we need to force an integer
// since the json package defaults to float64
var intCode int
err = json.Unmarshal(rawMap["code"], &intCode)
if err == nil {
e.Code = intCode
return nil
}
return json.Unmarshal(rawMap["code"], &e.Code)
}
func (e *RequestError) Error() string {
return fmt.Sprintf("error, status code: %d, message: %s", e.HTTPStatusCode, e.Err)
}
func (e *RequestError) Unwrap() error {
return e.Err
}