Spring MVC的Controller统一异常处理:HandlerExceptionResolver

a、针对500异常的统一处理
1、实现HandlerExceptionResolver,重写resolveException方法

package com.liying.mango.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 异常信息统一处理器
 *
 * @author jqlin
 */
public class MyExceptionHandler implements HandlerExceptionResolver {
    private static final Logger log = Logger.getLogger(MyExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, 
            Object obj, Exception e) {
        //堆栈信息打印到错误的日志文件中
        log.error(e.getMessage(), e);
        
        //跳转到500页面
        return new ModelAndView("500");  
    }

}

 

2、最后,将HandlerExceptionResolver实现类配置到Spring配置文件中

<bean id="myExceptionHandler" class="com.liying.mango.common.interceptor.MyExceptionHandler" />

 

b、针对404异常的统一处理
web.xml 404配置

    <error-page>
        <error-code>404</error-code>
        <location>/page/404.jsp</location>
    </error-page>

 

posted on 2017-06-30 16:11  Ruthless  阅读(892)  评论(0编辑  收藏  举报