首先看springMVC的配置文件:html
<!-- 全局異常配置 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類。
java
能夠看到源碼中和上述配置對應的屬性;web
另外要注意的是日誌spring
<span style="font-size:14px;"><property name="warnLogCategory" value="WARN"></property></span>
級別設置爲WARN:json
也能夠實現HandlerExceptionResolver接口或者繼承SimpleMappingExceptionResolver,寫一個本身的異常處理程序
app
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()) { // 異常信息日誌入庫 } } }