Skip to content

Commit

Permalink
Wrap the context render panic.
Browse files Browse the repository at this point in the history
Panic handling middleware can test for this error and decide to
supress the error or not.
  • Loading branch information
danmux committed Dec 6, 2022
1 parent 80cd679 commit 5ebc439
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 5 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"time"

"github.com/gin-contrib/sse"

"github.com/gin-gonic/gin/binding"
"github.com/gin-gonic/gin/render"
)
Expand Down Expand Up @@ -922,7 +923,10 @@ func (c *Context) Render(code int, r render.Render) {
}

if err := r.Render(c.Writer); err != nil {
panic(err)
panic(Error{
Err: err,
Type: ErrorTypeRender,
})
}
}

Expand Down
15 changes: 13 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ import (
"time"

"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin/binding"
testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"

"github.com/gin-gonic/gin/binding"
testdata "github.com/gin-gonic/gin/testdata/protoexample"
)

var _ context.Context = (*Context)(nil)
Expand Down Expand Up @@ -655,6 +656,16 @@ func TestContextRenderPanicIfErr(t *testing.T) {
defer func() {
r := recover()
assert.Equal(t, "TestPanicRender", fmt.Sprint(r))

// confirm the recovered object is an error
err, ok := r.(error)
assert.True(t, ok)

// the error returned should be a gin render Error
e := Error{}
assert.True(t, errors.As(err, &e))
assert.ErrorContains(t, e.Unwrap(), "TestPanicRender")
assert.True(t, e.IsType(ErrorTypeRender))
}()
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
Expand Down

0 comments on commit 5ebc439

Please sign in to comment.