SpringMVC4.x学习系列之全局异常处理
程序编码方式: import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionControllerAdvice { private Logger log = LogManager.getLogger("ExceptionControllerAdvice"); @ExceptionHandler public String expAdvice(HttpServletRequest req, Exception ex){ req.setAttribute("ex", ex.getMessage()); log.error(ex); //返回错误提示页面,实际开发时可根据不同的异常类型区别对待。 return "errors/error"; } } XML配置方式: <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/error</prop> </props> </property> <property name="defaultErrorView" value="errors/error"/> </bean>