全局异常处理springmvc
一、实现HandlerExceptionResolver接口
/** * springmvc 全局异常处理 */ @Slf4j public class GlobalExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //1.一般写日志 e.printStackTrace(); log.info(String.format("服务报错了。%s", e.getMessage())); //2.短信或者邮件通知管理员 System.out.println("发邮件或者短信"); //3. ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message","你的网络异常,请稍后"); modelAndView.setViewName("error/exception"); return modelAndView; } }
二、springmvc.xml文件配置该bean
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置扫描包 --> <context:component-scan base-package="com.taotao.search.controller"></context:component-scan> <!--扫描配置文件--> <context:property-placeholder location="classpath:properties/*.properties"/> <!-- 配置注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean class="com.taotao.search.exception.GlobalExceptionResolver"/> <!--引入dubbo服务--> <dubbo:application name="taotao-search-web"/> <dubbo:registry protocol="zookeeper" address="192.168.1.123:2181"/> <dubbo:reference interface="com.taotao.search.service.SearchItemService" id="searchItemService" timeout="300000"/> </beans>