首先看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="WARN"></property> <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 --> <property name="defaultErrorView" value="errors/error"></property> <!-- 默认HTTP状态码 --> <property name="defaultStatusCode" value="500"></property> </bean> <!-- 全局异常配置 end -->
这里主要的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。
可以看到源码中和上述配置对应的属性;
另外要注意的是日志
<span style="font-size:14px;"><property name="warnLogCategory" value="WARN"></property></span>
级别设置为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()) { // 异常信息日志入库 } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 01:44:55