Issue
I'm using Spring 4.3.8.RELEASE. I want to set an error message for a particular Forbidden error. I have this in my controller. "response" is of the type "javax.servlet.HttpServletResponse".
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentLength(errorMsg.length());
byte[] buffer = new byte[10240];
final OutputStream output = response.getOutputStream();
output.write(buffer, 0, errorMsg.length());
output.flush();
However, the content doesn't seem to be getting returned, at least I can't see it in my unit test ...
final MvcResult result = mockMvc.perform(get(contextPath + "/myurl")
.contextPath(contextPath)
.principal(auth)
.param("param1", param1)
.param("param2", param2))
.andExpect(status().isForbidden())
.andReturn();
// Verify the error message is correct
final String msgKey = "error.code";
final String errorMsg = MessageFormat.format(resourceBundle.getString(msgKey), new Object[] {});
Assert.assertEquals("Failed to return proper error message.", errorMsg, result.getResponse().getContentAsString());
The assertion failed saying that the response string was empty. What is teh proper way to write the response back to the HttpServletResponse buffer?
Solution
You never write errorMsg
to output
or buffer
.
Something like
response.getWriter().write(errorMsg)
should fix the issue
Answered By - Philippe Marschall