-
Notifications
You must be signed in to change notification settings - Fork 233
fix: make error accessible to custom modules #2420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
72f4048
fix: updates
SkArchon c4fbb02
fix: updates
SkArchon d8aeac1
fix: updates
SkArchon 17ede0f
fix: updates
SkArchon 2c06f54
fix: updates
SkArchon 9ab859a
Merge branch 'main' into milinda/make-error-accessible
SkArchon 0b692a1
fix: updates
SkArchon 0e64631
fix: updates
SkArchon 45ad2c6
fix: updates
SkArchon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package context_error | ||
|
|
||
| import ( | ||
| "net/http" | ||
|
|
||
| "github.com/wundergraph/cosmo/router/core" | ||
| ) | ||
|
|
||
| const myModuleID = "contextErrorModule" | ||
|
|
||
| type ContextErrorModule struct { | ||
| ErrorValue error | ||
| } | ||
|
|
||
| type headerCapturingWriter struct { | ||
| http.ResponseWriter | ||
| ctx core.RequestContext | ||
| statusCode int | ||
| moduleReference *ContextErrorModule | ||
| hasError bool | ||
| headerWritten bool | ||
| } | ||
|
|
||
| func (w *headerCapturingWriter) checkAndSetError() { | ||
| if !w.hasError { | ||
| if err := w.ctx.Error(); err != nil { | ||
| w.moduleReference.ErrorValue = err | ||
| w.hasError = true | ||
| w.Header().Set("X-Has-Error", "true") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (w *headerCapturingWriter) WriteHeader(statusCode int) { | ||
| if !w.headerWritten { | ||
| w.statusCode = statusCode | ||
| w.checkAndSetError() | ||
| w.headerWritten = true | ||
| w.ResponseWriter.WriteHeader(statusCode) | ||
| } | ||
| } | ||
|
|
||
| func (w *headerCapturingWriter) Write(b []byte) (int, error) { | ||
| if !w.headerWritten { | ||
| w.checkAndSetError() | ||
| w.headerWritten = true | ||
| } | ||
|
|
||
| return w.ResponseWriter.Write(b) | ||
| } | ||
|
|
||
| // Flush implements http.Flusher to support streaming responses | ||
| func (w *headerCapturingWriter) Flush() { | ||
| if f, ok := w.ResponseWriter.(http.Flusher); ok { | ||
| f.Flush() | ||
| } | ||
| } | ||
|
|
||
| func (m *ContextErrorModule) RouterOnRequest(ctx core.RequestContext, next http.Handler) { | ||
| // Wrap the response writer to intercept writes | ||
| wrappedWriter := &headerCapturingWriter{ | ||
| ResponseWriter: ctx.ResponseWriter(), | ||
| ctx: ctx, | ||
| statusCode: 0, | ||
| moduleReference: m, | ||
| } | ||
|
|
||
| // Call the next handler with the wrapped writer | ||
| // This wrapped writer will be passed through to all subsequent handlers, | ||
| // including the pre-handler where authentication happens | ||
| next.ServeHTTP(wrappedWriter, ctx.Request()) | ||
| } | ||
|
|
||
| func (m *ContextErrorModule) Module() core.ModuleInfo { | ||
| return core.ModuleInfo{ | ||
| // This is the ID of your module, it must be unique | ||
| ID: myModuleID, | ||
| // The priority of your module, lower numbers are executed first | ||
| Priority: 1, | ||
| New: func() core.Module { | ||
| return &ContextErrorModule{} | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Interface guard | ||
| var ( | ||
| _ core.RouterOnRequestHandler = (*ContextErrorModule)(nil) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| package module_test | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| integration "github.com/wundergraph/cosmo/router-tests" | ||
| contexterror "github.com/wundergraph/cosmo/router-tests/modules/context-error" | ||
| "github.com/wundergraph/cosmo/router-tests/testenv" | ||
| "github.com/wundergraph/cosmo/router/core" | ||
| "github.com/wundergraph/cosmo/router/pkg/config" | ||
| ) | ||
|
|
||
| func TestContextErrorModule(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| t.Run("error is captured in context when authentication fails", func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| authenticators, _ := integration.ConfigureAuth(t) | ||
| accessController, err := core.NewAccessController(core.AccessControllerOptions{ | ||
| Authenticators: authenticators, | ||
| AuthenticationRequired: true, | ||
| SkipIntrospectionQueries: false, | ||
| IntrospectionSkipSecret: "", | ||
| }) | ||
| require.NoError(t, err) | ||
|
|
||
| cfg := config.Config{ | ||
| Modules: map[string]interface{}{ | ||
| "contextErrorModule": contexterror.ContextErrorModule{}, | ||
| }, | ||
| } | ||
|
|
||
| testenv.Run(t, &testenv.Config{ | ||
| RouterOptions: []core.Option{ | ||
| core.WithAccessController(accessController), | ||
| core.WithModulesConfig(cfg.Modules), | ||
| core.WithCustomModules(&contexterror.ContextErrorModule{}), | ||
| }, | ||
| }, func(t *testing.T, xEnv *testenv.Environment) { | ||
| // Operations with an invalid token should fail | ||
| header := http.Header{ | ||
| "Authorization": []string{"Bearer invalid"}, | ||
| } | ||
| res, err := xEnv.MakeRequest(http.MethodPost, "/graphql", header, strings.NewReader(`{"query":"{ employees { id } }"}`)) | ||
| require.NoError(t, err) | ||
| defer res.Body.Close() | ||
| require.Equal(t, http.StatusUnauthorized, res.StatusCode) | ||
| data, err := io.ReadAll(res.Body) | ||
| require.NoError(t, err) | ||
| require.Contains(t, string(data), "unauthorized") | ||
|
|
||
| // Verify the X-Has-Error header is set when authentication fails | ||
| require.Equal(t, "true", res.Header.Get("X-Has-Error")) | ||
| }) | ||
| }) | ||
|
|
||
| t.Run("error is captured in context when subgraph fails", func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| cfg := config.Config{ | ||
| Modules: map[string]interface{}{ | ||
| "contextErrorModule": contexterror.ContextErrorModule{}, | ||
| }, | ||
| } | ||
|
|
||
| testenv.Run(t, &testenv.Config{ | ||
| RouterOptions: []core.Option{ | ||
| core.WithModulesConfig(cfg.Modules), | ||
| core.WithCustomModules(&contexterror.ContextErrorModule{}), | ||
| }, | ||
| Subgraphs: testenv.SubgraphsConfig{ | ||
| Products: testenv.SubgraphConfig{ | ||
| Middleware: func(handler http.Handler) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| _, _ = w.Write([]byte(`{"errors":[{"message":"Internal server error","extensions":{"code":"INTERNAL_SERVER_ERROR"}}]}`)) | ||
| }) | ||
| }, | ||
| }, | ||
| }, | ||
| }, func(t *testing.T, xEnv *testenv.Environment) { | ||
| res := xEnv.MakeGraphQLRequestOK(testenv.GraphQLRequest{ | ||
| Query: `{ employees { id details { forename surname } notes } }`, | ||
| }) | ||
|
|
||
| // Verify the response contains errors from the subgraph failure | ||
| require.Contains(t, res.Body, "errors") | ||
| require.Contains(t, res.Body, "Failed to fetch from Subgraph") | ||
|
|
||
| // Verify the X-Has-Error header is set when subgraph fails | ||
| require.Equal(t, "true", res.Response.Header.Get("X-Has-Error")) | ||
| }) | ||
| }) | ||
|
|
||
| t.Run("no error in context when request succeeds", func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| cfg := config.Config{ | ||
| Modules: map[string]interface{}{ | ||
| "contextErrorModule": contexterror.ContextErrorModule{}, | ||
| }, | ||
| } | ||
|
|
||
| testenv.Run(t, &testenv.Config{ | ||
| RouterOptions: []core.Option{ | ||
| core.WithModulesConfig(cfg.Modules), | ||
| core.WithCustomModules(&contexterror.ContextErrorModule{}), | ||
| }, | ||
| }, func(t *testing.T, xEnv *testenv.Environment) { | ||
| res := xEnv.MakeGraphQLRequestOK(testenv.GraphQLRequest{ | ||
| Query: `query MyQuery { employee(id: 1) { id } }`, | ||
| }) | ||
|
|
||
| require.Equal(t, `{"data":{"employee":{"id":1}}}`, res.Body) | ||
|
|
||
| // Verify the X-Has-Error header is NOT set when request succeeds | ||
| require.Empty(t, res.Response.Header.Get("X-Has-Error")) | ||
| }) | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.