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

首先看springMVC的配置文件:

     
          
              
                  
                 errors/error     
                 errors/err     
                  
              
              
                  
                 500     
                 404     
                  
              
              
              
              
              
              
              
          
     

这里主要的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。

可以看到源码中和上述配置对应的属性;


springMVC --全局异常处理(两种方式)_第1张图片

另外要注意的是日志

级别设置为WARN:

springMVC --全局异常处理(两种方式)_第2张图片


也可以实现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】,深入springMVC)