From 11f2321b0224c7cc1cc471fc2b126e6ea709b9da Mon Sep 17 00:00:00 2001 From: Donson Date: Tue, 22 Sep 2026 11:52:40 +0800 Subject: [PATCH] fix(context): classify render errors without losing existing flags --- context.go | 3 ++- context_test.go | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 788b00bb..0b028f3b 100644 --- a/context.go +++ b/context.go @@ -1210,7 +1210,8 @@ func (c *Context) Render(code int, r render.Render) { if err := r.Render(c.Writer); err != nil { // Pushing error to c.Errors - _ = c.Error(err) + renderErr := c.Error(err) + renderErr.Type |= ErrorTypeRender c.Abort() } } diff --git a/context_test.go b/context_test.go index cef488c9..fdfff932 100644 --- a/context_test.go +++ b/context_test.go @@ -1140,7 +1140,46 @@ func TestContextRenderIfErr(t *testing.T) { c.Render(http.StatusOK, &TestRender{}) - assert.Equal(t, errorMsgs{&Error{Err: errTestRender, Type: 1}}, c.Errors) + assert.Equal(t, errorMsgs{&Error{Err: errTestRender, Type: ErrorTypePrivate | ErrorTypeRender}}, c.Errors) + assert.Equal(t, c.Errors, c.Errors.ByType(ErrorTypeRender)) + assert.True(t, c.IsAborted()) +} + +type failingJSONMarshaler struct { + err error +} + +func (m failingJSONMarshaler) MarshalJSON() ([]byte, error) { + return nil, m.err +} + +func TestContextRenderJSONErrorType(t *testing.T) { + for _, typ := range []ErrorType{ErrorTypePrivate, ErrorTypePublic, ErrorTypeBind | ErrorTypePrivate} { + t.Run(fmt.Sprintf("type_%d", typ), func(t *testing.T) { + original := &Error{Err: errTestRender, Type: typ, Meta: "render metadata"} + var captured *Context + called := false + router := New() + router.GET("/", func(c *Context) { + captured = c + c.JSON(http.StatusOK, failingJSONMarshaler{err: original}) + }, func(c *Context) { + called = true + }) + + router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + + require.Len(t, captured.Errors, 1) + assert.Same(t, original, captured.Errors[0]) + assert.Equal(t, typ|ErrorTypeRender, captured.Errors[0].Type) + assert.Equal(t, "render metadata", captured.Errors[0].Meta) + require.ErrorIs(t, captured.Errors[0], errTestRender) + assert.Len(t, captured.Errors.ByType(ErrorTypeRender), 1) + assert.Len(t, captured.Errors.ByType(typ), 1) + assert.True(t, captured.IsAborted()) + assert.False(t, called) + }) + } } // Tests that the response is serialized as JSON