首页 > 代码库 > springMVC --全局异常处理(两种方式)

springMVC --全局异常处理(两种方式)

首先看springMVC的配置文件:

<!-- 全局异常配置 start -->     
     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">     
         <property name="exceptionMappings">     
             <props>     
                 <prop key="java.lang.Exception">errors/error</prop>     
                 <prop key="java.lang.Throwable">errors/err</prop>     
             </props>     
         </property>     
         <property name="statusCodes">     
             <props>     
                 <prop key="errors/error">500</prop>     
                 <prop key="errors/404">404</prop>     
             </props>     
         </property>     
         <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 -->     
         <property name="warnLogCategory" value=http://www.mamicode.com/"WARN">     >

这里基本的类是SimpleMappingExceptionResolver类。和他的父类AbstractHandlerExceptionResolver类。

能够看到源代码中和上述配置相应的属性;


技术分享

另外要注意的是日志

<span style="font-size:14px;"><property name="warnLogCategory" value=http://www.mamicode.com/"WARN">

级别设置为WARN:

技术分享


也能够实现HandlerExceptionResolver接口或者继承SimpleMappingExceptionResolver,写一个自己的异常处理程序

public class SpringMVCSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {
	
	public static final Log log = LogFactory.getLog(SpringMVCSimpleMappingExceptionResolver.class);
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView mv = null;
		String accept = request.getHeader("accept");
        if (accept != null && !(accept.indexOf("application/json") > -1 
        		|| (request.getHeader("X-Requested-With") != null 
        		&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            mv = super.doResolveException(request, response, handler, ex);
        } else {
            try { 
            	// json 请求返回
                PrintWriter writer = response.getWriter();  
                writer.write(Return.failure((ex.getMessage())));
                writer.flush();
            } catch (IOException e) {
            	if (log.isInfoEnabled()) {
            		log.info(StringUtil.getTrace(e));
            	}
            }
        }
        doLog((HandlerMethod) handler, ex);
        return mv;
	}
	
	/**
	 * 记录异常日志
	 * 
	 * @param handler
	 * @param excetpion
	 */
	private void doLog(HandlerMethod handler, Exception excetpion) {
        if (log.isEnabledExceptionDb()) {
        	// 异常信息日志入库
        }
	}	
}

springMVC --全局异常处理(两种方式)