remove panic in Render

Change-Id: Ifd7778ec44ea87d18b2156c97c88130f3ec72022
This commit is contained in:
Tevic 2022-01-26 13:05:15 +08:00
parent 580e7da6ee
commit e5196bec1f
4 changed files with 13 additions and 19 deletions

View File

@ -894,7 +894,8 @@ func (c *Context) Render(code int, r render.Render) {
} }
if err := r.Render(c.Writer); err != nil { if err := r.Render(c.Writer); err != nil {
panic(err) c.Error(err)
c.Abort()
} }
} }

View File

@ -642,25 +642,21 @@ func TestContextBodyAllowedForStatus(t *testing.T) {
assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError)) assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))
} }
type TestPanicRender struct{} type TestErrorRender struct{}
func (*TestPanicRender) Render(http.ResponseWriter) error { var errTestPanicRender = errors.New("TestPanicRender")
return errors.New("TestPanicRender")
func (*TestErrorRender) Render(http.ResponseWriter) error {
return errTestPanicRender
} }
func (*TestPanicRender) WriteContentType(http.ResponseWriter) {} func (*TestErrorRender) WriteContentType(http.ResponseWriter) {}
func TestContextRenderPanicIfErr(t *testing.T) { func TestContextRenderPanicIfErr(t *testing.T) {
defer func() {
r := recover()
assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
}()
w := httptest.NewRecorder() w := httptest.NewRecorder()
c, _ := CreateTestContext(w) c, _ := CreateTestContext(w)
c.Render(http.StatusOK, &TestErrorRender{})
c.Render(http.StatusOK, &TestPanicRender{}) assert.Equal(t, errorMsgs{&Error{Err: errTestPanicRender, Type: 1}}, c.Errors)
assert.Fail(t, "Panic not detected")
} }
// Tests that the response is serialized as JSON // Tests that the response is serialized as JSON

View File

@ -54,10 +54,7 @@ var (
// Render (JSON) writes data with custom ContentType. // Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) { func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil { return WriteJSON(w, r.Data)
panic(err)
}
return
} }
// WriteContentType (JSON) writes JSON ContentType. // WriteContentType (JSON) writes JSON ContentType.

View File

@ -39,12 +39,12 @@ func TestRenderJSON(t *testing.T) {
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
} }
func TestRenderJSONPanics(t *testing.T) { func TestRenderJSONError(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
data := make(chan int) data := make(chan int)
// json: unsupported type: chan int // json: unsupported type: chan int
assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) }) assert.Error(t, (JSON{data}).Render(w))
} }
func TestRenderIndentedJSON(t *testing.T) { func TestRenderIndentedJSON(t *testing.T) {