-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors.go
More file actions
95 lines (76 loc) · 1.8 KB
/
errors.go
File metadata and controls
95 lines (76 loc) · 1.8 KB
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
94
95
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package errors
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"github.com/codesphere-cloud/cs-go/api/openapi_client"
)
type TimedOutError struct {
msg string
}
func (e *TimedOutError) Error() string {
return e.msg
}
func TimedOut(operation string, timeout time.Duration) *TimedOutError {
return &TimedOutError{
msg: fmt.Sprintf("%s timed out after %s", operation, timeout.String()),
}
}
type NotFoundError struct {
msg string
}
func (e *NotFoundError) Error() string {
return e.msg
}
func NotFound(msg string) *NotFoundError {
return &NotFoundError{
msg: msg,
}
}
type DuplicatedError struct {
msg string
}
func (e *DuplicatedError) Error() string {
return e.msg
}
func Duplicated(msg string) *DuplicatedError {
return &DuplicatedError{
msg: msg,
}
}
type APIErrorResponse struct {
Status int `json:"status"`
Title string `json:"title"`
Detail string `json:"detail"`
TraceId string `json:"traceId"`
}
func FormatAPIError(r *http.Response, err error) error {
if err == nil {
return nil
}
if r == nil {
r = &http.Response{
StatusCode: -1,
}
}
if r.Request == nil {
r.Request = &http.Request{URL: &url.URL{}}
}
openAPIErr, ok := err.(*openapi_client.GenericOpenAPIError)
if !ok {
return fmt.Errorf("unexpected error %d at URL %s: %w", r.StatusCode, r.Request.URL, err)
}
body := openAPIErr.Body()
if len(body) == 0 {
return fmt.Errorf("unexpected error %d at URL %s: %w", r.StatusCode, r.Request.URL, err)
}
var apiErr APIErrorResponse
if json.Unmarshal(body, &apiErr) != nil {
return fmt.Errorf("unexpected error %d at URL %s: %w", r.StatusCode, r.Request.URL, err)
}
return fmt.Errorf("codesphere API returned error %d (%s): %s", apiErr.Status, apiErr.Title, apiErr.Detail)
}