首页 > 代码库 > 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 --全局异常处理(两种方式)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。