Exception code
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
private void setResponse(String msg) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
JSONObject res = new
res.put("error_code", ResponseCode.ERROR.getCode());
res.put("err_msg", msg);
res.put("data", null);
out.append(res.toString())
out.flush();
out.close();
throw new ForbiddenException();
}
Report an exception
getWriter() has already been called for this response
The solution is as follows
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
private void setResponse(String msg) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
ServletOutputStream out = response.getOutputStream();
try {
JSONObject res = new JSONObject();
res.put("error_code", ResponseCode.ERROR.getCode());
res.put("err_msg", msg);
res.put("data", null);
String json = new ObjectMapper().writeValueAsString(res);
out.write(json.getBytes());
out.flush();
out.close();
throw new ForbiddenException();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Note that printwriter should not be used, try catch, close the stream in finally,