java.lang.IllegalStateException: getOutputStream() has already been called for this response

前情提要:

1. 本项目为前后端分离项目,采用JSON数据进行通信。
2. 此异常出现在后端的异常统一处理方法出
3. 正常本机情况均不会出现,但是在服务器上部署就常抛出此异常

统一的异常处理
@ExceptionHandler(Exception.class)
    public void handleCustomException(Exception e, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = null;
        RestResult result = null;
        if (e instanceof CustomException){
            // 可设置不同的HTTP状态
            response.setStatus(200);
            CustomException ex = (CustomException) e;
            result = new RestResult(ex.getResultCode());
        }else if(e instanceof RuntimeException){
            response.setStatus(500);
            result = ResultGenerator.genFailResult(e.getMessage());
        }else {
            response.setStatus(500);
            result = new RestResult(500,"未知错误,请联系管理员");
        }
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result)); // a.此处不同版本的JSON处理可能会导致这个问题
            writer.flush();
            writer.close();  // b.不关闭流也将直接导致此异常的抛出,当然本机是没有问题的,服务器上才会有。
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }

相关说明

1. 网上一大堆关于此问题都是关于Jsp中outputStreamwriter流冲突了,因Jsp默认对象out实际调用的是response.getWriter(),而JSP不允许同时使用response.getWriter()和response.getOutoutStream(),错误就是这么出现的,在页面上加out.clear();out = pageContext.pushBody();可以解决,但这是针对JSP页面的,和前后端分离没关系。
2. 上面代码中a处可能出现相关流的冲突,部分版本的JSON序列化时好像会调用outputStream导致问题产生,a处写法是没有问题的。最后记住一定得关闭流,只是刷新了还不够。

你可能感兴趣的:(Java)