add httperrors tests
This commit is contained in:
@@ -13,12 +13,12 @@ import (
|
||||
|
||||
// SendErrorJSON makes {error: blah, details: blah} json body and responds with error code
|
||||
func SendErrorJSON(w http.ResponseWriter, r *http.Request, code int, err error, details string) {
|
||||
logDetails(r, code, err, details)
|
||||
log.Printf("[DEBUG] %s", errDetailsMsg(r, code, err, details))
|
||||
render.Status(r, code)
|
||||
render.JSON(w, r, map[string]interface{}{"error": err.Error(), "details": details})
|
||||
}
|
||||
|
||||
func logDetails(r *http.Request, code int, err error, details string) {
|
||||
func errDetailsMsg(r *http.Request, code int, err error, details string) string {
|
||||
uinfoStr := ""
|
||||
if user, e := GetUserInfo(r); e == nil {
|
||||
uinfoStr = user.Name + "/" + user.ID + " - "
|
||||
@@ -35,6 +35,6 @@ func logDetails(r *http.Request, code int, err error, details string) {
|
||||
srcFileInfo = fmt.Sprintf(" [caused by %s:%d]", strings.Join(fnameElems[len(fnameElems)-3:], "/"), line)
|
||||
}
|
||||
|
||||
log.Printf("[DEBUG] %s - %v - %d - %s%s - %s%s",
|
||||
return fmt.Sprintf("%s - %v - %d - %s%s - %s%s",
|
||||
details, err, code, uinfoStr, strings.Split(r.RemoteAddr, ":")[0], q, srcFileInfo)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSendErrorJSON(t *testing.T) {
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/error" {
|
||||
t.Log("http err request", r.URL)
|
||||
SendErrorJSON(w, r, 500, errors.New("error 500"), "error details 123456")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(404)
|
||||
}))
|
||||
|
||||
defer ts.Close()
|
||||
|
||||
resp, err := http.Get(ts.URL + "/error")
|
||||
require.Nil(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 500, resp.StatusCode)
|
||||
|
||||
assert.Equal(t, `{"details":"error details 123456","error":"error 500"}`+"\n", string(body))
|
||||
}
|
||||
|
||||
func TestErrorDetailsMsg(t *testing.T) {
|
||||
callerFn := func() {
|
||||
req, err := http.NewRequest("GET", "https://example.com/test?k1=v1&k2=v2", nil)
|
||||
require.Nil(t, err)
|
||||
msg := errDetailsMsg(req, 500, errors.New("error 500"), "error details 123456")
|
||||
assert.Equal(t, "error details 123456 - error 500 - 500 - - https://example.com/test?k1=v1&k2=v2 [caused by app/rest/httperrors_test.go:45]", msg)
|
||||
}
|
||||
callerFn()
|
||||
}
|
||||
Reference in New Issue
Block a user