-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
90 lines (77 loc) · 2.23 KB
/
handler.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
80
81
82
83
84
85
86
87
88
89
90
package server
import "net/http"
import (
errs "errors"
"fmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"strings"
)
//stackTracer is an error containing stack trace
type stackTracer interface {
StackTrace() errors.StackTrace
}
// HTTPError represents a handler error. It provides methods for a HTTP status
// code and embeds the built-in error interface.
type HTTPError interface {
error
Status() int
}
// StatusError represents an error with an associated HTTP status code.
type StatusError struct {
Code int
Err error
}
//NewStatusError creates new StatusError
func NewStatusError(code int, err string) StatusError {
return StatusError{code, errs.New(err)}
}
//ToStatusError creates new StatusError
func ToStatusError(code int, err error) StatusError {
return StatusError{code, err}
}
//Error allows StatusError to satisfy the error interface.
func (se StatusError) Error() string {
return se.Err.Error()
}
//Status returns our HTTP status code.
func (se StatusError) Status() int {
return se.Code
}
//StackTrace returns stacktrace of child error or nil
func (se StatusError) StackTrace() errors.StackTrace {
if se, ok := se.Err.(stackTracer); ok {
return se.StackTrace()
}
return nil
}
// The Handler struct that takes a configured Env and a function matching
// our useful signature.
type Handler struct {
H func(w http.ResponseWriter, r *http.Request) error
}
// ServeHTTP allows our Handler type to satisfy http.Handler.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := h.H(w, r)
if err != nil {
if err, ok := err.(stackTracer); ok {
stackTrace := make([]string, len(err.StackTrace()))
for i, f := range err.StackTrace() {
stackTrace[i] = fmt.Sprintf("%+s", f)
}
fmt.Println(strings.Join(stackTrace, "\n"))
}
switch e := errors.Cause(err).(type) {
case HTTPError:
// We can retrieve the status here and write out a specific
// HTTP status code.
log.Printf("HTTP %d - %s\n", e.Status(), e)
WriteJSON(e.Status(), map[string]string{"error": e.Error()}, w)
default:
// Any error types we don't specifically look out for default
// to serving a HTTP 500
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
}
}