统一异常处理类 全项目只有一个 写了注解标注的Java类 就不要在.xml文件中配置了
import com.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 修饰类,表明类是controller的全局配置类
* 三种全局配置:异常处理方案、绑定数据方案、绑定参数方案
* 统一异常处理类 只有一个 有了异常处理类 便不需要在.xml中配置
*/
//ControllerAdvice 意思是返回全部
//如果是通过继承或实现接口来实现 返回的是ModelAndView 不适合前后端分离 分离只需要model
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
//用于修饰方法,会在controller出现异常后调用,用于处理捕获到的异常
//注解用来指明异常的处理类型
@ExceptionHandler(Exception.class)
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
//e.getMessage()异常名字
//e.getStackTrace()异常具体信息
logger.error("服务器发生异常:"+ e.getMessage());
for(StackTraceElement element : e.getStackTrace()){
logger.error(element.toString());
}
/**
* 判断是用户的请求还是服务器的请求 服务器不用重定向到500
*/
String xRequestWith = request.getHeader("x-request-with");
if("XMLHttpRequest".equals(xRequestWith)){
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(CommunityUtil.getJSONString(1,"服务器异常"));
}else {
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
json转string放在工具类中了
//公有的 静态的
// 编码 提示信息 业务数据
public static String getJSONString(int code, String msg, Map<String, Object> map) {
JSONObject json = new JSONObject();
json.put("code", code);
json.put("msg", msg);
if (map != null) {
//遍历key的集合 得到key
for (String key : map.keySet()) {
json.put(key, map.get(key));
}
}
return json.toJSONString();
}
//重载 丢给上面处理
public static String getJSONString(int code, String msg) {
return getJSONString(code, msg, null);
}
//重载 交给上面处理
public static String getJSONString(int code) {
return getJSONString(code, null, null);
}