要求:既能返回ajax提交请求的异常信息,又能以指定的错误页面返回异常信息
***自定义异常
如果抛出此异常,系统会以json格式向前台返回异常信息
* 使用方式: throw new MyException("这里填入异常信息,会发送到前台")
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
// 异常信息
private String message;
public MyException() {
super();
}
public MyException(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
***指定的异常页面
此异常类型用来向前台返回页面
public class ReturnViewException extends Exception{
private static final long serialVersionUID = 1L;
//异常信息
public String message;
public ReturnViewException (String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
***逻辑处理
public class CustomHandleException implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
//判断是否为ajax请求,默认不是
boolean isAjaxRequest = false;
//这段代码能够得知是否为ajax请求,也就是我们说的json请求
if(!StringUtils.isBlank(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")){
isAjaxRequest = true;
}
//如果是ajax请求
if(isAjaxRequest) {
MyException myException = null;
if(exception instanceof MyException) {
myException = (MyException) exception;
}else {
//如果抛出的不是系统自定义的异常则重新构造一个未知错误异常
//这里我就也有CustomException省事了,实际中应该要再定义一个新的异常
myException = new MyException ("系统未知错误,请联系管理员");
}
String message = myException.getMessage();
//向前台返回错误信息
ModelAndView model = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView();
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", 500);
map.put("message", message);
view.setAttributesMap(map);
model.setView(view);
return model;
}else {
//如果不是ajax请求 那么异常后需要返回页面
ReturnViewException returnViewException = null;
//如果抛出的异常类型是我们预想的,会想前台返回我们指定在参数里的页面
if(exception instanceof ReturnViewException) {
returnViewException = (ReturnViewException) exception;
}else {
//系统默认跳转到error页面
returnViewException = new ReturnViewException("error");
}
ModelAndView model = new ModelAndView();
model.setViewName(returnViewException.getMessage());
return model;
}
}
}
***配置springmvc.xml的全局异常处理器
<!-- 配置全局异常处理器 -->
<bean id="customHandleException" class="com.CIB.exception.CustomHandleException"/>
网友评论