今天又重新整理了一下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我也不太了解,可以搜下资料看下。