* fix #1070

* test: add more tests
This commit is contained in:
Kevin Wan
2021-12-29 21:34:28 +08:00
committed by GitHub
parent b8ea16a88e
commit 62266d8f91
4 changed files with 27 additions and 9 deletions

View File

@@ -14,13 +14,17 @@ var (
)
// Error writes err into w.
func Error(w http.ResponseWriter, err error) {
func Error(w http.ResponseWriter, err error, fns ...func(w http.ResponseWriter, err error)) {
lock.RLock()
handler := errorHandler
lock.RUnlock()
if handler == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
if len(fns) > 0 {
fns[0](w, err)
} else {
http.Error(w, err.Error(), http.StatusBadRequest)
}
return
}

View File

@@ -95,6 +95,18 @@ func TestError(t *testing.T) {
}
}
func TestErrorWithHandler(t *testing.T) {
w := tracedResponseWriter{
headers: make(map[string][]string),
}
Error(&w, errors.New("foo"), func(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), 499)
})
assert.Equal(t, 499, w.code)
assert.True(t, w.hasBody)
assert.Equal(t, "foo", strings.TrimSpace(w.builder.String()))
}
func TestOk(t *testing.T) {
w := tracedResponseWriter{
headers: make(map[string][]string),