/
errors.go
79 lines (65 loc) · 1.99 KB
/
errors.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
package ginruntime
import (
"fmt"
"net/http"
"github.com/oslokommune/common-lib-go/httpcomm"
)
// Server response status code and associated error message
type ApiError struct {
Detail error
Reason string
Status int
}
func (this *ApiError) Error() string {
statusText := http.StatusText(this.Status)
if this.Reason != "" {
return fmt.Sprintf("%s: %s", statusText, this.Reason)
}
return statusText
}
// Converts `err` to an `*ApiError` if it's not nil.
func Normalize(err error) *ApiError {
if err == nil {
return nil
}
switch err := err.(type) {
case *ApiError:
return err
// TODO: See if we can avoid having a depencency towards httpcomm in the future
case *httpcomm.HTTPError:
if err.StatusCode == http.StatusNotFound {
return NotFound(err.Error())
} else if err.StatusCode == http.StatusForbidden {
return Forbidden(err.Error())
} else {
return FailedDependency(err.Error())
}
default:
// Vi returnerer ikke feilmeldingen her for å unngå å potensielt sende sensitiv informasjon
return InternalServerError("internal server error")
}
}
func BadRequest(reason string) *ApiError {
return &ApiError{Status: http.StatusBadRequest, Reason: reason}
}
func Unauthorized(reason string) *ApiError {
return &ApiError{Status: http.StatusUnauthorized, Reason: reason}
}
func Forbidden(reason string) *ApiError {
return &ApiError{Status: http.StatusForbidden, Reason: reason}
}
func NotFound(reason string) *ApiError {
return &ApiError{Status: http.StatusNotFound, Reason: reason}
}
func UnprocessableEntity(reason string) *ApiError {
return &ApiError{Status: http.StatusUnprocessableEntity, Reason: reason}
}
func FailedDependency(reason string) *ApiError {
return &ApiError{Status: http.StatusFailedDependency, Reason: reason}
}
func InternalServerError(reason string) *ApiError {
return &ApiError{Status: http.StatusInternalServerError, Reason: reason}
}
func NotImplemented(reason string) *ApiError {
return &ApiError{Status: http.StatusNotImplemented, Reason: reason}
}