-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp_error.go
More file actions
104 lines (86 loc) · 2.93 KB
/
http_error.go
File metadata and controls
104 lines (86 loc) · 2.93 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
96
97
98
99
100
101
102
103
104
// httperror provides a golang error-compatible type for escalating HTTP status codes alongside with the cause descriptions.
// Copyright 2019 KaaIoT Technologies, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httperror
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
// HTTPError is a convenience error type for returning function processing results back to callers.
type HTTPError struct {
statusCode int
description string
}
// Error function transforms HTTPError into a human-readable string.
func (p *HTTPError) Error() string {
if p == nil {
return ""
}
return p.description
}
// New constructs a new HTTPError.
func New(code int, format string, a ...interface{}) error {
return &HTTPError{
statusCode: code,
description: fmt.Sprintf(format, a...),
}
}
// StatusCode is a convenience function for extracting HTTP Status Code from error types.
// It returns 200 for nil errors, embedded StatusCode for HTTPError instances, and 500 in every other case.
func StatusCode(err error) int {
if err == nil {
return http.StatusOK
}
var httpError *HTTPError
if errors.As(err, &httpError) {
return httpError.statusCode
}
return http.StatusInternalServerError
}
// StatusText is a convenience function for extracting HTTP status text from error types.
func StatusText(err error) string {
return http.StatusText(StatusCode(err))
}
// Write to the response writer a status code and a JSON-encoded message based on the provided error.
// The payload will look like:
// {
// "message": "error writing to DB"
// }
// In case the status code is 500 (Internal Server Error), the message will always be "Internal Server Error".
// Write does not end the request; the caller should ensure no further writes are done to w.
func Write(w http.ResponseWriter, err error) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
code := StatusCode(err)
w.WriteHeader(code)
var message string
if code == http.StatusInternalServerError {
message = http.StatusText(code)
} else {
message = err.Error()
}
_ = json.NewEncoder(w).Encode(struct {
Message string `json:"message"`
}{Message: message})
}
// Equal compares error status codes and contents.
func Equal(err1, err2 error) bool {
switch {
case err1 == nil && err2 == nil:
return true
case (err1 == nil) != (err2 == nil):
return false
default:
return StatusCode(err1) == StatusCode(err2) && err1.Error() == err2.Error()
}
}