Suppress body when handling a no content (204) "error"

Fixes gh-18136
This commit is contained in:
Andy Wilkinson
2019-09-24 16:01:18 +01:00
parent 35ad5cd011
commit c613418451
2 changed files with 30 additions and 2 deletions

View File

@@ -94,8 +94,11 @@ public class BasicErrorController extends AbstractErrorController {
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<Map<String, Object>>(status);
}
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}

View File

@@ -92,13 +92,23 @@ public class BasicErrorControllerMockMvcTests {
}
@Test
public void testErrorWithResponseStatus() throws Exception {
public void testErrorWithNotFoundResponseStatus() throws Exception {
MvcResult result = this.mockMvc.perform(get("/bang")).andExpect(status().isNotFound()).andReturn();
MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")).andReturn();
String content = response.getResponse().getContentAsString();
assertThat(content).contains("Expected!");
}
@Test
public void testErrorWithNoContentResponseStatus() throws Exception {
MvcResult result = this.mockMvc.perform(get("/noContent").accept("some/thing"))
.andExpect(status().isNoContent()).andReturn();
MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error"))
.andExpect(status().isNoContent()).andReturn();
String content = response.getResponse().getContentAsString();
assertThat(content).isEmpty();
}
@Test
public void testBindingExceptionForMachineClient() throws Exception {
// In a real server the response is carried over into the error dispatcher, but
@@ -174,6 +184,11 @@ public class BasicErrorControllerMockMvcTests {
throw error;
}
@RequestMapping("/noContent")
public void noContent() throws Exception {
throw new NoContentException("Expected!");
}
}
}
@@ -187,6 +202,15 @@ public class BasicErrorControllerMockMvcTests {
}
@ResponseStatus(HttpStatus.NO_CONTENT)
private static class NoContentException extends RuntimeException {
NoContentException(String string) {
super(string);
}
}
private class ErrorDispatcher implements RequestBuilder {
private MvcResult result;
@@ -203,6 +227,7 @@ public class BasicErrorControllerMockMvcTests {
MockHttpServletRequest request = this.result.getRequest();
request.setDispatcherType(DispatcherType.ERROR);
request.setRequestURI(this.path);
request.setAttribute("javax.servlet.error.status_code", this.result.getResponse().getStatus());
return request;
}