SpringMVC异常处理

/**
 * 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"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值