Skip to content

Commit c233125

Browse files
committed
Don't render error view if response is committed
This commit prevents the default error view from rendering itself if the response has been committed already. In this case, it is impossible to change the HTTP response status and write a proper response - trying to do so often results in a `IllegalStateException` since the response body has already been written to. Fixes gh-11580
1 parent 42c1ce6 commit c233125

File tree

2 files changed

+100
-4
lines changed

2 files changed

+100
-4
lines changed

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2017 the original author or authors.
2+
* Copyright 2012-2018 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -25,6 +25,9 @@
2525
import javax.servlet.http.HttpServletRequest;
2626
import javax.servlet.http.HttpServletResponse;
2727

28+
import org.apache.commons.logging.Log;
29+
import org.apache.commons.logging.LogFactory;
30+
2831
import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
2932
import org.springframework.beans.BeansException;
3033
import org.springframework.beans.factory.ObjectProvider;
@@ -206,6 +209,8 @@ public ConditionOutcome getMatchOutcome(ConditionContext context,
206209
*/
207210
private static class SpelView implements View {
208211

212+
private static final Log logger = LogFactory.getLog(SpelView.class);
213+
209214
private final NonRecursivePropertyPlaceholderHelper helper;
210215

211216
private final String template;
@@ -225,16 +230,32 @@ public String getContentType() {
225230
@Override
226231
public void render(Map<String, ?> model, HttpServletRequest request,
227232
HttpServletResponse response) throws Exception {
233+
if (response.isCommitted()) {
234+
String message = getMessage(model);
235+
logger.error(message);
236+
return;
237+
}
228238
if (response.getContentType() == null) {
229239
response.setContentType(getContentType());
230240
}
231-
Map<String, Object> map = new HashMap<>(model);
232-
map.put("path", request.getContextPath());
233-
PlaceholderResolver resolver = new ExpressionResolver(getExpressions(), map);
241+
PlaceholderResolver resolver = new ExpressionResolver(getExpressions(), model);
234242
String result = this.helper.replacePlaceholders(this.template, resolver);
235243
response.getWriter().append(result);
236244
}
237245

246+
private String getMessage(Map<String, ?> model) {
247+
StringBuilder builder = new StringBuilder();
248+
builder.append("Cannot render error page for request [")
249+
.append(model.get("path")).append("]");
250+
if (model.get("message") != null) {
251+
builder.append(" and exception [").append(model.get("message"))
252+
.append("]");
253+
}
254+
return builder.append("] as the response has already been committed.")
255+
.append("As a result, the response may have the wrong status code.")
256+
.toString();
257+
}
258+
238259
private Map<String, Expression> getExpressions() {
239260
if (this.expressions == null) {
240261
synchronized (this) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* Copyright 2012-2018 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.boot.autoconfigure.web.servlet.error;
18+
19+
import org.junit.Rule;
20+
import org.junit.Test;
21+
22+
import org.springframework.boot.autoconfigure.AutoConfigurations;
23+
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
24+
import org.springframework.boot.test.rule.OutputCapture;
25+
import org.springframework.boot.web.servlet.error.ErrorAttributes;
26+
import org.springframework.mock.web.MockHttpServletRequest;
27+
import org.springframework.mock.web.MockHttpServletResponse;
28+
import org.springframework.web.context.request.WebRequest;
29+
import org.springframework.web.servlet.View;
30+
import org.springframework.web.servlet.handler.DispatcherServletWebRequest;
31+
32+
import static org.hamcrest.Matchers.allOf;
33+
import static org.hamcrest.Matchers.containsString;
34+
35+
/**
36+
* Tests for {@link ErrorMvcAutoConfiguration}.
37+
*
38+
* @author Brian Clozel
39+
*/
40+
public class ErrorMvcAutoConfigurationTests {
41+
42+
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
43+
.withConfiguration(AutoConfigurations.of(ErrorMvcAutoConfiguration.class));
44+
45+
@Rule
46+
public OutputCapture outputCapture = new OutputCapture();
47+
48+
@Test
49+
public void testDefaultViewWithResponseAlreadyCommitted() {
50+
this.contextRunner.run((context) -> {
51+
View errorView = context.getBean("error", View.class);
52+
ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class);
53+
DispatcherServletWebRequest webRequest =
54+
createCommittedWebRequest(new IllegalStateException("Exception message"));
55+
errorView.render(errorAttributes.getErrorAttributes(webRequest, true),
56+
webRequest.getRequest(), webRequest.getResponse());
57+
this.outputCapture.expect(allOf(
58+
containsString("Cannot render error page for request [/path]" +
59+
" and exception [Exception message]] as the response has already been committed."),
60+
containsString("As a result, the response may have the wrong status code.")));
61+
});
62+
}
63+
64+
protected DispatcherServletWebRequest createCommittedWebRequest(Exception e) {
65+
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path");
66+
MockHttpServletResponse response = new MockHttpServletResponse();
67+
DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, response);
68+
webRequest.setAttribute("javax.servlet.error.exception", e, WebRequest.SCOPE_REQUEST);
69+
webRequest.setAttribute("javax.servlet.error.request_uri", "/path", WebRequest.SCOPE_REQUEST);
70+
response.setCommitted(true);
71+
response.setOutputStreamAccessAllowed(false);
72+
response.setWriterAccessAllowed(false);
73+
return webRequest;
74+
}
75+
}

0 commit comments

Comments
 (0)