-
Notifications
You must be signed in to change notification settings - Fork 11
/
error.go
93 lines (73 loc) · 2.02 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
87
88
89
90
91
92
93
package replicate
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// APIError represents an error returned by the Replicate API
type APIError struct {
// Type is a URI that identifies the error type.
Type string `json:"type,omitempty"`
// Title is a short human-readable summary of the error.
Title string `json:"title,omitempty"`
// Status is the HTTP status code.
Status int `json:"status,omitempty"`
// Detail is a human-readable explanation of the error.
Detail string `json:"detail,omitempty"`
// Instance is a URI that identifies the specific occurrence of the error.
Instance string `json:"instance,omitempty"`
}
func unmarshalAPIError(resp *http.Response, data []byte) *APIError {
apiError := APIError{}
err := json.Unmarshal(data, &apiError)
if err != nil {
apiError.Detail = fmt.Sprintf("Unknown error: %s", err)
}
if apiError.Status == 0 && resp != nil {
apiError.Status = resp.StatusCode
}
return &apiError
}
func (e APIError) Error() string {
components := []string{}
if e.Type != "" {
components = append(components, e.Type)
}
if e.Title != "" {
components = append(components, e.Title)
}
if e.Detail != "" {
components = append(components, e.Detail)
}
output := strings.Join(components, ": ")
if output == "" {
output = "unknown error"
}
if e.Instance != "" {
output = fmt.Sprintf("%s (%s)", output, e.Instance)
}
return output
}
func (e *APIError) WriteHTTPResponse(w http.ResponseWriter) {
status := http.StatusBadGateway
if e.Status != 0 {
status = e.Status
}
w.WriteHeader(status)
err := json.NewEncoder(w).Encode(e)
if err != nil {
err = fmt.Errorf("failed to write error response: %w", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// ModelError represents an error returned by a model for a failed prediction.
type ModelError struct {
Prediction *Prediction `json:"prediction"`
}
func (e *ModelError) Error() string {
if e.Prediction == nil {
return "unknown model error"
}
return fmt.Sprintf("model error: %s", e.Prediction.Error)
}