Skip to content

Commit

Permalink
Introduce a render.Error returned from the render panic.
Browse files Browse the repository at this point in the history
This can be used to wrap underlying errors to convey more detail
about what errored, in particular this is used to wrap the error
returned in a panic, so that 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 7fe2ee0
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
2 changes: 1 addition & 1 deletion render/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var (
// Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil {
panic(err)
panic(Error{err: err})
}
return
}
Expand Down
13 changes: 13 additions & 0 deletions render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ type Render interface {
WriteContentType(w http.ResponseWriter)
}

// Error is used to specifically wrap errors related to rendering
type Error struct {
err error
}

func (e Error) Error() string {
return fmt.Sprintf("render: %v", e.err)
}

func (e Error) Unwrap() error {
return e.err
}

var (
_ Render = JSON{}
_ Render = IndentedJSON{}
Expand Down
27 changes: 24 additions & 3 deletions render/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"strconv"
"strings"
"testing"

testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
Expand Down Expand Up @@ -43,8 +43,29 @@ func TestRenderJSONPanics(t *testing.T) {
w := httptest.NewRecorder()
data := make(chan int)

// json: unsupported type: chan int
assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) })
t.Run("panic", func(t *testing.T) {
// json: unsupported type: chan int
assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) })
})

t.Run("panic returns error", func(t *testing.T) {
func() {
defer func() {
p := recover()

err, ok := p.(error)
assert.True(t, ok)

e := Error{}
assert.True(t, errors.As(err, &e))

assert.ErrorContains(t, e.Unwrap(), "unsupported type")
}()

// Will panic
(JSON{data}).Render(w)
}()
})
}

func TestRenderIndentedJSON(t *testing.T) {
Expand Down

0 comments on commit 7fe2ee0

Please sign in to comment.