Skip to content

Attempt to reset Servlet response before calling ExceptionHandlers #31104

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,11 @@ protected ModelAndView doResolveHandlerMethodException(HttpServletRequest reques
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
}

// attempt to reset the response, as maybe a partial successful response is being written.
if (!response.isCommitted()) {
response.reset();
}

ServletWebRequest webRequest = new ServletWebRequest(request, response);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,24 @@ void resolveExceptionViaMappedHandler() throws Exception {
assertThat(this.response.getContentAsString()).isEqualTo("DefaultTestExceptionResolver: IllegalStateException");
}

@Test // gh-30702
void attemptToResetResponseBeforeResolveException() throws UnsupportedEncodingException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
this.resolver.setMappedHandlerClasses(HttpRequestHandler.class);
this.resolver.setApplicationContext(ctx);
this.resolver.afterPropertiesSet();

IllegalStateException ex = new IllegalStateException();
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
mockHttpServletResponse.getWriter().print("test");
ModelAndView mav = this.resolver.resolveException(this.request, mockHttpServletResponse, handler, ex);

assertThat(mav).as("Exception was not handled").isNotNull();
assertThat(mav.isEmpty()).isTrue();
assertThat(mockHttpServletResponse.getContentAsString()).isEqualTo("DefaultTestExceptionResolver: IllegalStateException");
}


private void assertMethodProcessorCount(int resolverCount, int handlerCount) {
assertThat(this.resolver.getArgumentResolvers().getResolvers()).hasSize(resolverCount);
Expand Down