web.xml:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/view/exception/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/view/exception/500.jsp</location>
</error-page>
BaseController.java
protected final Logger logger = LoggerFactory.getLogger(BaseController.class);
/** 基于@ExceptionHandler异常处理 */
@ExceptionHandler
public ModelAndView exp(HttpServletRequest request, HttpServletResponse response,Exception exception) {
request.setAttribute("ex", exception);
exception.printStackTrace();
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With") != null && request.getHeader(
"X-Requested-With").indexOf("XMLHttpRequest") > -1))) { // 判断是否ajax请求
Map<String, Object> map = new HashMap<String, Object>();
map.put("error",exception.getMessage());
exception.printStackTrace();
return new ModelAndView("exception/error", map);
} else {
try {
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
JSONObject jsonObject = new JSONObject();
jsonObject.put("error",exception.getMessage());
writer.write(jsonObject.toString());
writer.flush();
writer.close();
exception.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
ajax请求:
$.ajax({
url : url + "?r=" + (new Date().getTime()),
dataType : dataType,
data : data,
method : "post",
success : function(ret) {
if (dataType == 'json') {
if(ret.error=="" || ret.error==null || ret.error=='undefined'){
callback.call(this, ret);
}else{
layer.open({//layer 弹出框插件
icon: 5,
title: '错误提示',
content:"糟糕,网页访问出错啦!"
})
}
} else {
ret = eval("(" + ret + ")");
if (ret.success == 'undefined'|| ret.success == undefined) {
callback.call(this, ret);
} else {
if (ret.success == true) {
callback.call(this, ret);
} else {
alert(ret.error);
}
}
}
unMask(domId);
},
error : function(ret, textStatus, errorThrown) {
unMask(domId);
alert(ret.responseText);
}
})