/**
* SpringMVC异常处理
* Created by aiyaoxin on 2018/1/2 10:51
*/
public class ExceptionResolver implements HandlerExceptionResolver {
private Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("code", Code.ERROR.getValue());
modelAndView.addObject("error", ExceptionUtils.getStackTrace(e));
modelAndView.addObject("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
String accept = httpServletRequest.getHeader("Accept");
String xhr = httpServletRequest.getHeader("X-Requested-With");
if (xhr != null || accept.contains("application/json")) {// ajax请求或要求返回数据为json格式
modelAndView.setView(new MappingJackson2JsonView());
modelAndView.addObject("msg", e.getMessage());
} else {
modelAndView.addObject("msg", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
modelAndView.setViewName("error");
}
logger.error("Internal Server Error", e);
httpServletRequest.getSession().getId();
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return modelAndView;
}
}
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
<meta charset="utf-8">
<title>${status != null ? status: "404"}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/vue.min.js"></script>
</head>
<body>
<div id="app" class="container text-center">
<div class="page-header">
<h1>
${msg != null ? msg: "Page Not Found"}
<a href="javascript:;" class="text-muted btn-sm" title="点击显示异常信息" @click="showError()">Info</a>
</h1>
</div>
<div class="text-left">
<textarea class="form-control" style="height: 80%" readonly v-show="errorInfo">
${error}
</textarea>
</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
errorInfo: false,
},
methods: {
showError: function () {
this.errorInfo = !this.errorInfo;
}
}
});
</script>
</body>
</html>
<!-- 全局异常处理 -->
<bean class="com.common.ExceptionResolver"/>