-
Notifications
You must be signed in to change notification settings - Fork 1
/
httperrors.go
48 lines (41 loc) · 1.37 KB
/
httperrors.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
package httperrors
import (
"encoding/json"
"fmt"
"net/http"
)
// Some code copied from https://github.com/labstack/echo/blob/master/echo.go
// WritableError is an interface for errors that can be written to http responses as JSON
type WritableError interface {
error
WriteJSON(w http.ResponseWriter) error
}
// HTTPError represents an http error that occurred while handling a request
type HTTPError struct {
StatusCode int `json:"-"`
Message interface{} `json:"message"`
}
// New creates a new HTTPError instance
// message can be an error, the error message is then used as message
// the message is optional but multiple messages are not supported
func New(statusCode int, message interface{}) *HTTPError {
he := &HTTPError{StatusCode: statusCode, Message: http.StatusText(statusCode)}
if message != nil {
he.Message = message
}
return he
}
// Error makes HTTPError compatible with the error interface.
func (he *HTTPError) Error() string {
return fmt.Sprintf("%d - %v", he.StatusCode, he.Message)
}
// WriteJSON allows to write the http error to a ResponseWriter
// for implemantation of the WritableError interface
func (he *HTTPError) WriteJSON(w http.ResponseWriter) error {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(he.StatusCode)
if err, ok := he.Message.(error); ok {
he.Message = err.Error()
}
return json.NewEncoder(w).Encode(he)
}