springMVC的HandlerExceptionResolver接口

今天又重新整理了一下HandlerExceptionResolver这个接口

spring MVC的Controller出现异常的默认处理是响应一个500状态码,这个处理显得不那么完美

在 springmvc 中可能存在着多个控制器,各个控制器又存在着众多请求处理方法。若在每个方法上都进行异常处理,那样实在是过于繁琐。

因此 springmvc 提供了 HandlerExceptionResolver 接口来统一处理异常。

例子:

public class  ExceptionHandler   implements HandlerExceptionResolver {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);
	
 	@Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest,
		HttpServletResponse httpServletResponse, Object handler, Exception e) {
        	try {
            		if (null != e) {
                		HandlerMethod handlerMethod = (HandlerMethod) handler;
                		handlerMethod.getMethodAnnotation(RequestMapping.class);
                		String method = handlerMethod.getMethod().getName();
                		LOGGER.error("method[{}] error:  {}", method, e.getMessage());             
            		}
        	} catch (Exception e1) {
            		LOGGER.error("", e1);
        	}
        	return null;
    	}

}

 这一段是对于异常的处理,可以实现存入数据库、写入文件、或者直输出等操作,当web.xml中有相应的error-page配置,则可以在实现resolveException方法时返回null,或者也可以自己写错误返回页。

ModelAndView modelAndView = new ModelAndView("errorPage");

return modelAndView;

例子是通过HandlerMethod来得到controller中requestMapping方法的,然后进行错误输出

最后,还需要将自己的HandlerExceptionResolver实现类配置到Spring配置文件中,或者加上@Component注解

 <bean id="exceptionHandler"
          class="com.zz.ExceptionHandler">
  </bean>
 
对于HandlerMethod我也不太了解,可以搜下资料看下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值