使用Spring实现异常统一处理【三】--java.lang.IllegalStateException: STREAM问题的解决

在《使用Spring实现异常统一处理【二】》中,在处理JSON转换的异常时,自定义异常处理类,自个就报java.lang.IllegalStateException: STREAM错误,原因为:在该自定义异常处理类中,使用了response.getWriter()进行错误信息输出,而Spring的MappingJackson2HttpMessageConverter应该通过response.getOutputStream(),已获取了输出流。

在servlet标准中,是不允许同时使用response.getWriter()和response.getOutputStream()的,所以报java.lang.IllegalStateException: STREAM错误。

       原因知道了,解决方案就有谱了:在获取response.getWriter()出错时,就改用response.getOutputStream()输出流。

       关键代码

String returnStr="{error:'"+exception.getMessage()+"'}";
try {
	writer = response.getWriter();
	writer.write(returnStr);
	writer.flush();
	writer.close();
} catch (Exception e) {
	try {
	OutputStream output=response.getOutputStream();
	output.write(returnStr.getBytes("UTF-8"));
	output.flush();
	output.close();
	} catch (Exception e1) {
	e1.printStackTrace();
	}
}

 
  

       完整代码

public class CustomSimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception) {

		if (handler == null) {
			return null;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		if (method == null) {
			return null;
		}
		Class methodReturnType=method.getReturnType();
		ResponseBody responseBody = AnnotationUtils.findAnnotation(method,
				ResponseBody.class);
		if (methodReturnType.getName().equals("void")||responseBody != null) {
			PrintWriter writer;
			String returnStr="{error:'"+exception.getMessage()+"'}";
			try {
				writer = response.getWriter();
				writer.write(returnStr);
			    writer.flush();
				writer.close();
			} catch (Exception e) {
				try {		
					OutputStream output=response.getOutputStream();
					output.write(returnStr.getBytes("UTF-8"));
					output.flush();
					output.close();					
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

		} else {
			String viewName = super.determineViewName(exception, request);			
			
			if (viewName != null) {// JSP格式返回

				Integer statusCode = super.determineStatusCode(request,
						viewName);
				if (statusCode != null) {
					super.applyStatusCodeIfPossible(request, response,
							statusCode);
				}
				return super.getModelAndView(viewName, exception, request);
			}
		}
		return new ModelAndView();

	}// doResolveException

}



		
		
		
		
			
				
				/exception/errorpage
				/exception/errorpage
			
		
		
		 

<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true"%>




JSP Page


	

Hello World!error!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ${exception}




  

你可能感兴趣的:(Spring)