Skip to content

Fixed issue where GrailsExceptionResolver masks original exception with GrailsWebRequest cast failure. - #16396

Merged
jdaugherty merged 2 commits into
apache:8.0.xfrom
ruthst00:fix/16129-grailswebrequest-cast
Sep 28, 2026
Merged

jdaugherty merged 2 commits into
apache:8.0.xfrom
ruthst00:fix/16129-grailswebrequest-cast

Conversation

@ruthst00

@ruthst00 ruthst00 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Root Cause

Two unconditional casts to GrailsWebRequest in the URL mapping layer would throw ClassCastException when Spring's RequestContextHolder held a plain ServletRequestAttributes (not a GrailsWebRequest). This happens during exception resolution when the Grails filter hasn't had a chance to upgrade the request attributes. The ClassCastException then replaced the original application exception in GrailsExceptionResolver, masking the real error.

A DispatcherServlet other than the Grails one - the one MockMvc runs, for example - binds a plain ServletRequestAttributes over the GrailsWebRequest that GrailsWebRequestFilter bound. Guarding the casts alone left GrailsExceptionResolver forwarding to a controller error handler with a null GrailsWebRequest, so the original exception was still replaced.

Changes Made

1. grails-doc/src/en/guide/theWebLayer/urlmappings/mappingToResponseCodes.adoc

Adds a new NOTE admonition block just before the existing WARNING about error handler stack overflows.

2. grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java

Changes:

  • New import: GrailsWebRequest is now imported directly.

  • resolveViewOrForward() — two-phase error handling with defensive guards:

    1. Phase 1 (mapping resolution) wrapped in try/catch(RuntimeException): The call to matchStatusCode() and the subsequent parameter merging are now wrapped in a try/catch. If the mapping resolution itself throws (e.g., a closure-based controller: mapping that reads Grails request state that wasn't initialized), the exception is logged as an error and the method returns the default mv (the /error view with the original exception). This prevents the mapping failure from replacing the original exception.
    2. mapsToView / mapsToController booleans are computed inside the try block and used in the second phase, cleanly separating resolution from dispatch.
    3. Guard for missing GrailsWebRequest before forwarding to a controller: Before attempting to forward to an error-handling controller, the code now checks GrailsWebRequest.lookup(request) == null. If there is no GrailsWebRequest (e.g., a MockMvc test without Grails filters), it logs a warning and returns the default mv instead of crashing.
  • forwardRequest() — request-scoped lookup instead of thread-local:
    Changed from WebUtils.retrieveGrailsWebRequest() (which reads the thread-local RequestContextHolder) to GrailsWebRequest.lookup(request) (which reads the GrailsWebRequest stored on the request object itself). This correctly finds the GrailsWebRequest even when a non-Grails DispatcherServlet has overwritten the thread-local with plain ServletRequestAttributes.

3. grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy

Changes:

  • New shared infrastructure:

    • Four string constants (GRAILS, PLAIN_OVER_GRAILS, PLAIN, NOTHING) describe the four possible request-attribute binding states under test.
    • A shared MockServletContext and StaticWebApplicationContext field, with a cleanup() method that resets RequestContextHolder and closes the web context after each feature.
  • Two existing tests fixed: The two pre-existing tests that forward to a controller (resolveViewOrForward with a controller mapping) now call bind(GRAILS, request, response) to set up the GrailsWebRequest that the fixed code now requires before forwarding.

  • Three new @Issue('#16129') data-driven feature methods:

    1. "an error handler mapped to #handler is forwarded to with #attributes bound" — Verifies the happy path: when a GrailsWebRequest is available (either directly bound or stored on the request under plain attributes), the error handler controller is successfully forwarded to, the response's forwardedUrl is set, and the original exception is preserved as the cause of the wrapped exception on the request attribute.
      Covers: static controller name, closure-based controller name, and HTTP-method-map action — all with GRAILS or PLAIN_OVER_GRAILS attributes.

    2. "the default error view renders the exception when #handler cannot be forwarded to with #attributes bound" — Verifies the graceful degradation path: when there is no GrailsWebRequest (only plain attributes or nothing), or when the mapping closure itself throws, the result is the /error view name, no forward URL, and the original exception is preserved in the model. Covers all the failure scenarios including a broken mapping closure.

    3. "an error handler mapped to a view renders with #attributes bound" — Verifies that view-mapped error handlers (not controller-mapped) work correctly under all four attribute states (GRAILS, PLAIN_OVER_GRAILS, PLAIN, NOTHING), since view resolution doesn't require a GrailsWebRequest.

  • New helper methods:

    • resolverFor(Closure mappings, boolean controllerMappings) — builds a fully wired GrailsExceptionResolver with a real DefaultUrlMappingsHolder, optional GrailsControllerUrlMappings wrapper, a stub ViewResolver, and a StaticWebApplicationContext.
    • bind(String attributes, request, response) — sets up the thread-local request attributes in one of the four states.

4. grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java

Change: Adds a new package-private static method lookupWebRequest().

This is the central fix for the URL mappings layer. Instead of casting RequestContextHolder.getRequestAttributes() directly to GrailsWebRequest (which fails when MockMvc's DispatcherServlet has overwritten the thread-local with a plain ServletRequestAttributes), this method:

  1. Returns the thread-local directly if it is a GrailsWebRequest.
  2. If it's a plain ServletRequestAttributes, falls back to GrailsWebRequest.lookup(request) — reading the GrailsWebRequest that GrailsWebRequestFilter stored on the request object.
  3. Returns null if neither applies.

All other URL mapping classes are updated to call this method instead of doing the raw cast themselves.

5. grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/AbstractUrlMappingInfo.java

Changes:

  • evaluateName() (the no-arg overload): Now calls UrlMappingUtils.lookupWebRequest() instead of casting RequestContextHolder.getRequestAttributes() directly.

  • evaluateNameForValue(Object value, GrailsWebRequest webRequest) — improved Javadoc and two new guards:

    1. Closure guard: If webRequest is null but there are request attributes bound (meaning a non-Grails dispatcher is active without GrailsWebRequestFilter), the closure is not called and null is returned. This prevents the closure from running without its expected Grails delegate and potentially throwing or returning garbage. Previously, the closure would be called with a null delegate.
    2. HTTP-method-map guard: When webRequest is null, the code now falls back to currentRequest() (a new private helper that extracts the HttpServletRequest from a plain ServletRequestAttributes). If there is no request at all, null is returned instead of throwing a NullPointerException.
  • New private helper currentRequest(): Uses a Java 16+ pattern-matching instanceof to safely extract the HttpServletRequest from ServletRequestAttributes, returning null if the bound attributes are not servlet-based.

6. grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlMappingInfo.java

Changes:

  • Removes the now-unnecessary imports of RequestContextHolder and GrailsWebRequest (the logic has moved to AbstractUrlMappingInfo and UrlMappingUtils).
  • getActionName() now calls the no-arg evaluateNameForValue(actionName) (inherited from AbstractUrlMappingInfo) instead of manually casting RequestContextHolder.getRequestAttributes() to GrailsWebRequest and passing it in. Also switches from var to explicit String type for clarity.

7. grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlCreator.java

Changes:

  • Two RequestContextHolder casts replaced with UrlMappingUtils.lookupWebRequest() in createURL(Map, String) and createURLInternal(...). This ensures the context path is correctly read from the GrailsWebRequest even when MockMvc's dispatcher has overwritten the thread-local.
  • Context path null-check: The includeContextPath branch now first fetches the context path into a local variable and only appends it if it is non-null. This avoids appending a null/empty string when no GrailsWebRequest is available.
  • Removes the now-unused import org.springframework.web.context.request.RequestContextHolder.

8. grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/RegexUrlMapping.java

Change: In the URL creation path that prepends the context path, the direct RequestContextHolder cast to GrailsWebRequest is replaced with UrlMappingUtils.lookupWebRequest(). Removes the now-unused import org.springframework.web.context.request.RequestContextHolder.

9. grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingInfoRequestAttributesSpec.groovy

Change: A brand-new Spock specification that exhaustively tests how URL mapping info resolves names and creates URLs under all four request-attribute binding states.

Feature methods:

  • 'names a mapping states resolve with #attributes bound' — Static controller/action/view/URI names resolve correctly regardless of which attributes are bound.
  • 'a name closure reads the GrailsWebRequest with #attributes bound' — A closure-based action name (e.g., action: { params.section }) correctly reads request parameters when a GrailsWebRequest is available (directly or via fallback).
  • 'a name closure is not called when the bound attributes have no GrailsWebRequest' — When only plain ServletRequestAttributes are bound (no GrailsWebRequest), closures are not invoked and return null safely.
  • 'a name closure is called without a delegate when no request attributes are bound' — When nothing is bound, a closure that doesn't need a delegate (e.g., { 'show' }) still works.
  • 'a map of HTTP methods selects the name for the request method with #attributes bound' — HTTP-method maps work with GRAILS, PLAIN_OVER_GRAILS, and PLAIN attributes; return null when nothing is bound.
  • 'a mapping creates its URL with the context path of the GrailsWebRequest with #attributes bound' — Context path is included in generated URLs only when a GrailsWebRequest is available.
  • 'the default URL creator uses the context path of the GrailsWebRequest with #attributes bound' — Same context-path behavior verified for DefaultUrlCreator directly.

Fixes #16129

Generated with Claude Sonnet 4.6 via Cline API Provider inside IntelliJ 2025.3.3

Contributor Checklist

Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.

Issue and Scope

  • This PR is linked to an existing issue that has been acknowledged or approved by the project team. If no approved issue exists, please give background on why this change is necessary. Tickets are preferred for release change log history.
  • This PR addresses the complete scope of the linked issue. Partial implementations or unfinished work should not be submitted for review.
  • This PR contains a single, focused change. Unrelated changes should be submitted as separate pull requests.
  • This PR targets the correct branch for the type of change:
    • Patch release branches (e.g., 7.0.x): Bug fixes only. No new features or API changes.
    • Minor release branches (e.g., 7.1.x): New features are welcome, but breaking existing APIs must be avoided.
    • Major release branches (e.g., 8.0.x): Reserved for major changes. Breaking API changes are permitted.

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR. All code contributions are expected to include appropriate test coverage.
  • I have verified that all existing tests pass by running ./gradlew build --rerun-tasks.
    • 3 Existing tests fail due to TTL race condition and database state pollution between parallel test runs
  • My code follows the project's code style guidelines. I have run ./gradlew codeStyle and resolved any violations. See Code Style for details.
  • This PR does not include mass reformatting, style-only changes, or large-scale refactoring unless it was explicitly approved in the linked issue. Unsolicited reformatting will not be accepted.
  • If generative AI tooling was used in preparing this contribution, a quality model was used to ensure contributions are consistent with the project's quality standards.

Licensing and Attribution

Documentation

  • If this PR introduces user-facing changes, I have included or updated the relevant documentation.
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide.
  • If this PR introduces breaking changes or changes that require user action during an upgrade, I have updated the Upgrade Notes for the corresponding version in the Grails Guide.
  • The PR description clearly explains what was changed and why.

First-time contributors: Please read our Contributing Guide before submitting.
Pull requests that appear to be auto-generated, incomplete, or unrelated to an approved issue may be
closed to help maintainers focus on reviewed and planned work. We appreciate your understanding.

…uest

A DispatcherServlet other than the Grails one - the one MockMvc runs, for
example - binds a plain ServletRequestAttributes over the GrailsWebRequest
that GrailsWebRequestFilter bound. Guarding the casts alone left
GrailsExceptionResolver forwarding to a controller error handler with a
null GrailsWebRequest, so the original exception was still replaced.

- URL mapping names, reverse mappings and the default URL creator find the
  GrailsWebRequest the filter stored on the request when the bound
  attributes are plain
- Without one, a name closure is not called and resolves to null, and a map
  of HTTP methods is keyed by the method of the bound request. With no
  attributes bound at all, a closure is still called without a delegate
- GrailsExceptionResolver forwards to a controller error handler only when
  the request has a GrailsWebRequest, and an error handler that cannot be
  resolved no longer replaces the exception being resolved: it is logged
  and the /error view renders the original exception
- The default URL creator no longer prefixes URLs with "null" when there is
  no context path

Fixes apache#16129

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @ruthst00 & thank you picking this up. I reviewed this PR with an LLM and have noted it's feedback below for others to review. I believe all of these issues are addressed in my latest push:

Guarding the cast is the right direction, but as it stands only a view-mapped status code is fixed. A controller-mapped one still loses the original exception, now to an NPE instead of a ClassCastException. Details are inline. I checked this in a local checkout by running resolveException with real URL mappings, and by reverting each production hunk against the new specs.

Beyond the inline comments:

  • The same unchecked (GrailsWebRequest) RequestContextHolder.getRequestAttributes() cast is still in RegexUrlMapping.createURLInternal and twice in DefaultUrlCreator. Those run when the error view renders a link under the same plain attributes. Since the issue asks that this path stop assuming a GrailsWebRequest, it makes sense to route them through the same lookup in this PR.

def resolver = new GrailsExceptionResolver() {

@Override
protected void forwardRequest(UrlMappingInfo forwarded, HttpServletRequest req,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overriding forwardRequest hides the part of this bug the PR doesn't fix yet (commenting here because GrailsExceptionResolver isn't in the diff). The real forwardRequest calls info.configure(WebUtils.retrieveGrailsWebRequest()), and retrieveGrailsWebRequest() returns null when the bound attributes aren't a GrailsWebRequest. populateParamsForMapping(null) then throws an NPE, which resolveViewOrForward wraps in a GrailsRuntimeException. So the original exception is still lost.

I ran resolveException against real mappings built by DefaultUrlMappingEvaluator, with a plain ServletRequestAttributes bound:

status mapping 8.0.x this PR
"500"(view: '/error') ClassCastException resolves (view set, status 500)
"500"(controller: 'errors', action: 'serverError') ClassCastException GrailsRuntimeException → NPE in populateParamsForMapping
"500"(controller: { 'errors' }, action: 'serverError') ClassCastException GrailsRuntimeException → UrlMappingException

Controller-mapped error handlers are common, so the resolver needs a fix as well. For the MockMvc case in the issue, GrailsWebRequestFilter has already stored the GrailsWebRequest on the request before the dispatcher rebinds plain attributes over it. So info.configure(GrailsWebRequest.lookup(request)) finds it; with just that change, the controller mapping forwards to /errors/serverError. When there's no GrailsWebRequest at all (the issue's direct resolveException reproduction), the forward can't be configured. Returning mv without forwarding would let the original exception reach the default error view. UrlMappingUtils.forwardRequestForUrlMappingInfo also dereferences GrailsWebRequest.lookup(request) without a null check, so that path needs the same guard.

RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, new MockHttpServletResponse()))

and: 'a UrlMappingInfo whose getControllerName() triggers a closure-based name resolution'
def info = Mock(UrlMappingInfo)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test passes with both production changes reverted (I put AbstractUrlMappingInfo and DefaultUrlMappingInfo back to 8.0.x and it stays green). UrlMappingInfo and UrlMappingsHolder are mocks, so nothing reads RequestContextHolder, and getControllerName() is stubbed to return 'errors'. The closure-based name resolution described in the and: label never happens.

Could this build real mappings with DefaultUrlMappingEvaluator and DefaultUrlMappingsHolder, and go through resolveException (the entry point from the issue) without overriding forwardRequest? Cover both a view mapping and a controller mapping, and assert that the returned ModelAndView's exception entry wraps the original exception. That version fails today for the controller mapping (see the comment on forwardRequest) and will pin the fix once it's in.

GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
org.springframework.web.context.request.RequestAttributes attrs =
RequestContextHolder.getRequestAttributes();
GrailsWebRequest webRequest = attrs instanceof GrailsWebRequest ? (GrailsWebRequest) attrs : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the frame from the issue's stack trace (getNamespace() → evaluateNameForValue(Object)), but no test fails if it's reverted. With only this hunk put back to the unconditional cast, all of AbstractUrlMappingInfoSafeCastSpec and GrailsExceptionResolverSpec still pass. The specs go through either getActionName(), which calls the two-arg overload directly, or a String controller name, which returns before the cast. A spec calling getNamespace() / getViewName() / getId() on a mapping with no namespace, while plain attributes are bound, would cover it.

Also, GrailsWebRequest.lookup() already does exactly this instanceof check. Use it, or the helper suggested on the closure branch below, here and in DefaultUrlMappingInfo.getActionName() instead of two inline copies with a fully-qualified RequestAttributes.


String name;
if (value instanceof Closure) {
if (webRequest == null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning null here changes more than the cast:

  • When nothing is bound, the closure used to run anyway, with a null delegate. A closure that doesn't touch the request, such as action: { 'show' }, resolved to show on 8.0.x and resolves to null now.
  • A controller name that comes back null makes getControllerName() throw UrlMappingException. So a status mapping with a closure controller still masks the original exception; the ClassCastException just becomes a UrlMappingException (last row of the table on the forwardRequest comment).

In the MockMvc case from the issue the GrailsWebRequest still exists: GrailsWebRequestFilter stored it on the request before the dispatcher bound plain attributes over it. When the bound attributes are a ServletRequestAttributes, GrailsWebRequest.lookup(((ServletRequestAttributes) attrs).getRequest()) recovers it, and the closure keeps evaluating against the real request. null would then only be returned when no GrailsWebRequest exists anywhere. A private helper for that lookup would also replace the inline copies in both files.

name = result != null ? result.toString() : null;
}
else if (value instanceof Map) {
if (webRequest == null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Selecting by HTTP method doesn't need a GrailsWebRequest: HiddenHttpMethod.effectiveMethod takes the HttpServletRequest, which a plain ServletRequestAttributes already has. As written, action: [GET: 'show', POST: 'save'] quietly resolves to null whenever the bound attributes aren't Grails'. Taking the request from the bound ServletRequestAttributes would keep this branch working. No spec covers the Map branch yet.

actionName == null
}

void 'getActionName does not throw ClassCastException when RequestContextHolder holds a plain ServletRequestAttributes'() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feature is identical to the one above: same mapping, same bound attributes, same info.actionName call. The one above is named for evaluateNameForValue(Object) but never reaches it. Also in this spec:

  • The empty-holder feature below is named for ClassCastException, but on 8.0.x it failed with an NPE (casting a null holder is fine).
  • The static controller-name feature passes on 8.0.x, because a String name returns before the cast.

A data-driven feature would cover the one-arg path this spec is missing. Run it over the public getters (namespace, controllerName, actionName, viewName, id), crossed with the holder state (GrailsWebRequest, plain ServletRequestAttributes, nothing bound) and the value shape (String, closure, method Map).

* {@link ServletRequestAttributes} instead of a {@link org.grails.web.servlet.mvc.GrailsWebRequest}.
*
* <p>This scenario arises when {@link org.grails.web.errors.GrailsExceptionResolver} resolves an
* exception: Spring's {@code DispatcherServlet} may have bound a {@code ServletRequestAttributes}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't quite how the plain attributes get there. In a Grails app, GrailsDispatcherServlet.buildRequestAttributes replaces a plain ServletRequestAttributes with a GrailsWebRequest, so exception resolution under Grails' own dispatcher always sees one. The plain attributes come either from a non-Grails dispatcher rebinding over the GrailsWebRequest that GrailsWebRequestFilter set (MockMvc's TestDispatcherServlet, as in the issue), or from code calling the resolver directly. Could the Javadoc, and the root-cause section of the PR description, say that?

@jdaugherty

Copy link
Copy Markdown
Contributor

@matrei @codeconsole can one of you review this too please? I believe I've fixed all of the issues I found with it.

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.9654%. Comparing base (a441334) to head (912be07).
⚠️ Report is 139 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...org/grails/web/errors/GrailsExceptionResolver.java 68.4210% 4 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16396        +/-   ##
==================================================
+ Coverage     57.4998%   57.9654%   +0.4656%     
- Complexity      22590      22969       +379     
==================================================
  Files            2129       2135         +6     
  Lines          103863     105149      +1286     
  Branches        18651      18972       +321     
==================================================
+ Hits            59721      60950      +1229     
+ Misses          35871      35823        -48     
- Partials         8271       8376       +105     
Files with missing lines Coverage Δ
...org/grails/web/mapping/AbstractUrlMappingInfo.java 86.2500% <100.0000%> (-1.4212%) ⬇️
...oovy/org/grails/web/mapping/DefaultUrlCreator.java 57.9439% <100.0000%> (+2.2835%) ⬆️
.../org/grails/web/mapping/DefaultUrlMappingInfo.java 54.9020% <100.0000%> (+9.2709%) ⬆️
...groovy/org/grails/web/mapping/RegexUrlMapping.java 69.2748% <100.0000%> (+1.5267%) ⬆️
...groovy/org/grails/web/mapping/UrlMappingUtils.java 61.2903% <100.0000%> (+14.9816%) ⬆️
...org/grails/web/errors/GrailsExceptionResolver.java 80.5556% <68.4210%> (+6.6425%) ⬆️

... and 28 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

ruthst00 added a commit to ruthst00/grails-core that referenced this pull request Sep 26, 2026
…ing the uncovered and partially covered branches in `GrailsExceptionResolver.java` identified from the Codecov PR apache#16396 report. All 45 tests pass with no style violations.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head 09834160c2 (base 8.0.x, merge base a441334507). It merges cleanly into the current 8.0.x at 0dab8a7263.

Thanks for sticking with this, @ruthst00. @jdaugherty's push (912be076d0) addressed his earlier review. I read the production changes again and they look good to me: the unchecked cast is gone from the name lookups and both URL creators, the resolver keeps the original exception when the error handler can't be resolved or forwarded to, and the tests build real mappings and go through resolveException. Most of my comments are about what has been added since then, c49632a0d9 and the merge commit.

Run locally at the head:

Module Tests Result
grails-web-mvc 78 pass
grails-web-url-mappings 279 pass

1. Please drop the geb.env change in gradle/functional-test-config.gradle

c49632a0d9 adds systemProperty('geb.env', 'test') for every Test task in every module that applies this script. It has nothing to do with #16129. None of the GebConfig.groovy files in the repository have an environments { test { ... } } block, so on CI it does nothing. If it was needed to get Geb tests running on your machine, please keep it local (for example in ~/.gradle/init.d) or open an issue describing what failed, so we can fix it properly.

2. Please move the 20 coverage tests into a separate PR

The tests added in c49632a0d9 cover parts of GrailsExceptionResolver that this PR doesn't change: log message formatting, findWrappedException, determineUri, isExcludedRequestParameter, the log flag caching and createStackFilterer. Tests for existing behaviour are welcome, but they belong in their own PR. This one should stay focused on the fix for #16129. Codecov's patch coverage only counts the lines this PR changes, and James's tests already cover those.

If you open the follow-up PR, please also look at these points:

  • resolveViewOrForward skips forward when response is already committed doesn't test what its name says. No GrailsWebRequest is bound, so resolveViewOrForward returns at the new GrailsWebRequest.lookup(request) == null check before it reaches response.isCommitted(). I changed response.committed = true to false and the spec still passed, 60 of 60. To test the committed branch, bind a GrailsWebRequest the way the #handler/#attributes features do. Also assert something more specific than result != null, such as the returned ModelAndView still holding the original exception.
  • Test through the public behaviour, not the implementation. resolveLogFlags is idempotent — config is consulted only once counts calls into a private cache, and resolveLogFlags reads false for all flags… is named after a private method. Both will break on a harmless refactor. The isExcludedRequestParameter and determineUri features call protected helpers directly. What users see is the logged message, so assert on getRequestLogMessage(...) output instead. The existing getRequestLogMessage masks excluded request parameters case-insensitively feature is a good model.
  • Some features repeat existing ones. The case-insensitive exclusion match is already covered by getRequestLogMessage masks excluded request parameters case-insensitively. The createStackFilterer fallback is already covered by the three falls back to building from config features. The new feature adds only the catch branch.
  • Style: use imports instead of the fully qualified org.grails.web.util.WebUtils and org.grails.core.exceptions.GrailsRuntimeException, and keep the new imports in order with the others (InvokerInvocationException and ControllerExecutionException are out of place).

3. Update the PR description

The description still describes the first commit. AbstractUrlMappingInfoSafeCastSpec no longer exists (it was replaced by UrlMappingInfoRequestAttributesSpec), and the description doesn't mention the changes to GrailsExceptionResolver, UrlMappingUtils, DefaultUrlCreator, RegexUrlMapping or the guide. The root cause section should also say where the plain attributes actually come from, as James asked in his review: a dispatcher other than the Grails one binding them over the GrailsWebRequest (as MockMvc does), or code calling the resolver directly. The first paragraph of the 912be076d0 commit message puts it well. The title is also cut off after "…with"; please complete it.

4. Clean up the history

09834160c2 merges the branch's own remote copy into itself, and PRs are merged here without squashing, so that merge commit would end up on 8.0.x. After removing c49632a0d9, please drop the merge commit too, for example by resetting the branch to 912be076d0 and force-pushing. The remaining history is then just the original fix followed by James's commit.

With these changes, I'm happy with it.

@matrei

matrei commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

One more thing, about the target branch. This bug is also on 7.0.x. All five unchecked (GrailsWebRequest) RequestContextHolder.getRequestAttributes() casts are there (AbstractUrlMappingInfo:124, DefaultUrlMappingInfo:203, DefaultUrlCreator:64 and :127, RegexUrlMapping:302), and GrailsExceptionResolver still configures the forward with WebUtils.retrieveGrailsWebRequest(). So a 7.x application tested with MockMvc loses the original exception in the same way. It's a bug fix with no API change, so it qualifies for 7.0.x.

However, it can't just be retargeted. Applying 0f09606b2c and 912be076d0 to origin/7.0.x conflicts in GrailsExceptionResolver, GrailsExceptionResolverSpec, AbstractUrlMappingInfo and DefaultUrlMappingInfo. The resolver change builds on code that only exists on 8.0.x: the guard against forwarding to a failing error handler twice, the captured-name handling and the status-code selection. On 7.0.x that part would need to be rewritten.

That leaves two options:

  1. Retarget this PR to 7.0.x, rework the fix for the older code, and reconcile it with the 8.0.x version during the merge-up.
  2. Merge this PR on 8.0.x once the items above are addressed, and open a separate backport PR for 7.0.x that adapts the fix to the older resolver.

I lean toward 2, since most of the rework would be in the resolver changes. @jdaugherty, since those are your changes, which do you prefer?

@ruthst00 ruthst00 changed the title Fixed issue where GrailsExceptionResolver masks original exception wi… Fixed issue where GrailsExceptionResolver masks original exception with GrailsWebRequest cast failure. Sep 26, 2026
@ruthst00
ruthst00 force-pushed the fix/16129-grailswebrequest-cast branch from 0983416 to 912be07 Compare September 26, 2026 18:13
@testlens-app

testlens-app Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 912be07
▶️ Tests: 166639 executed
⚪️ Checks: 176/176 completed


Learn more about TestLens at testlens.app/docs.

@ruthst00

Copy link
Copy Markdown
Contributor Author

@matrei, thank you for your thorough analysis of my latest changes and giving me clear instructions for backing out of the mess I made trying to address issues in the CodeCov report :o)

As instructed, I reset the PR branch to 912be07 which dropped the last two commits:

I then and force-pushed to set the history back to the original fix followed by @jdaugherty's commit.

Also updated the PR description to encompass all changes in the two remaining commits.

@jdaugherty

Copy link
Copy Markdown
Contributor

@matrei let's keep this focused on 8.0.x and we can backport as needed. I'm going to take another pass at this and look to see if this can be merged.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've confirmed all feedback was implemented and I'm good to merge this. On the PR descriptions, I think this is good enough and ready to merge once @matrei agrees.

@matrei we can backport once this is merged.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head 912be076d0 (base 8.0.x, merge base a441334507). It merges cleanly into the current 8.0.x at 7ce779e2e7, and 8.0.x hasn't touched any of the changed files since the merge base.

Thanks, @ruthst00, that's exactly what I was after. All the points from my last review are addressed:

  1. The geb.env change in gradle/functional-test-config.gradle is gone.
  2. The coverage tests for unchanged GrailsExceptionResolver behaviour are gone. The remaining tests cover the fix only.
  3. The title is complete, and the description now covers every changed file, including where the plain attributes come from.
  4. The history is the original fix followed by @jdaugherty's commit, with no merge commit.

The production code is unchanged from 912be076d0, which I had already read and was happy with. I also checked that no unchecked (GrailsWebRequest) RequestContextHolder.getRequestAttributes() cast is left anywhere in the repository.

Run locally on the PR merged into 7ce779e2e7, without the build cache:

Module Tests Result
grails-web-mvc (35 in GrailsExceptionResolverSpec) 53 pass
grails-web-url-mappings (20 in UrlMappingInfoRequestAttributesSpec) 279 pass
Checkstyle (main) and CodeNarc (test) for both modules clean

On the target branch: agreed, @jdaugherty, let's merge this on 8.0.x and do the 7.0.x backport as a separate PR afterwards.

Approving.

@jdaugherty
jdaugherty merged commit 5e35c2c into apache:8.0.x Sep 28, 2026
179 checks passed
@jdaugherty

Copy link
Copy Markdown
Contributor

Thank you @ruthst00 for your contribution and patience!

@jdaugherty jdaugherty added this to the grails:8.0.0-RC2 milestone Sep 28, 2026
@ruthst00

Copy link
Copy Markdown
Contributor Author

Thank you, @jdaugherty and @matrei for your careful review and guidance! Couldn't have done it without you :-)

jdaugherty added a commit that referenced this pull request Sep 28, 2026
…-7.0.x

Backport #16396 to 7.0.x: resolve error handlers and mapping names without a bound GrailsWebRequest
matrei pushed a commit to codeconsole/grails-core that referenced this pull request Sep 29, 2026
…uest

Backport of apache#16396 to 7.0.x.

A DispatcherServlet other than the Grails one - the one MockMvc runs, for
example - binds a plain ServletRequestAttributes over the GrailsWebRequest
that GrailsWebRequestFilter bound. The casts to GrailsWebRequest in the URL
mapping layer then threw a ClassCastException, which GrailsExceptionResolver
reported in place of the exception it was resolving.

- URL mapping names, the names a mapping captures from the URI ($controller,
  $action, ...), reverse mappings and the default URL creator find the
  GrailsWebRequest the filter stored on the request when the bound
  attributes are plain
- Without one, a name closure is not called and resolves to null, and a map
  of HTTP methods is keyed by the method of the bound request. With no
  attributes bound at all, a closure is still called without a delegate
- GrailsExceptionResolver forwards to a controller error handler only when
  the request has a GrailsWebRequest, and an error handler that cannot be
  resolved no longer replaces the exception being resolved: it is logged
  and the /error view renders the original exception
- The default URL creator no longer prefixes URLs with "null" when there is
  no context path

Fixes apache#16129

Co-authored-by: ruthes00 <ruthes00@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

GrailsExceptionResolver masks original exception with GrailsWebRequest cast failure

3 participants