-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
50 lines (42 loc) · 968 Bytes
/
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
package deepl
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
type HTTPError struct {
RequestURL string
Message string
StatusCode int
}
func (err HTTPError) Error() string {
if err.Message != "" {
return fmt.Sprintf("HTTP %d: %s (%s)", err.StatusCode, err.Message, err.RequestURL)
}
return fmt.Sprintf("HTTP %d: (%s)", err.StatusCode, err.RequestURL)
}
func HandleHTTPError(resp *http.Response) error {
httpError := HTTPError{
StatusCode: resp.StatusCode,
RequestURL: resp.Request.URL.String(),
}
if !strings.Contains(resp.Header.Get("Content-Type"), "json") {
httpError.Message = resp.Status
return httpError
}
body, err := io.ReadAll(resp.Body)
if err != nil {
httpError.Message = err.Error()
return httpError
}
var parseBody struct {
Message string `json:"message"`
}
if err := json.Unmarshal(body, &parseBody); err != nil {
return httpError
}
httpError.Message = parseBody.Message
return httpError
}