As mentioned in the previous article, an exception blocker is configured in the spring-servlet.xml and logs are recorded. If I need to do some other processing when an exception occurs, we can customize the exception Parser:
public class MyExceptionResolver implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object obj, Exception exception) {// TODO Auto-generated method stubModelAndView result=new ModelAndView("showError");result.addObject("exception", exception);return result;}
}
Then initialize in spring-servlcet.xml:
<bean id="exceptionResolver"class="com.zah.web.controller.MyExceptionHandler"/>
However, we can no longer define the following attributes in this bean:
<property name="defaultErrorView"><value>failure</value></property><property name="exceptionMappings"><props><prop key="java.sql.SQLException">showDBError</prop><prop key="java.lang.RuntimeException">showError</prop></props></property><property name="warnLogCategory" value="WARN"></property><property name="defaultStatusCode" value="500"></property>
You need to manually process the log:
public class MyExceptionResolver implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object obj, Exception exception) {// TODO Auto-generated method stubModelAndView result=new ModelAndView("showError");result.addObject("exception", exception);return result;}private Log warnLogger;public void setWarnLogCategory(String loggerName) {this.warnLogger = LogFactory.getLog(loggerName);}protected void logException(Exception ex, HttpServletRequest request) {if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {this.warnLogger.warn("Handler execution resulted in exception", ex);}}}
The writing is a bit bad. It's a record. In fact, you can look at the simplemappingexceptionresolver source code and extend the simplemappingexceptionresolver class to meet your own business needs.