1.模拟异常访问
@Controller
@RequestMapping("/test")
public class ExceptionTest {
@RequestMapping("/1")
public String test1() throws SysException{
try {
System.out.println(1/0);
} catch (Exception e) {
e.printStackTrace();
throw new SysException("除数为零");
}
return "success";
}
}
2.自定义异常类
public class SysException extends Exception{
private String message;
public SysException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
3.自定义异常处理器(实现HandlerExceptionResolver)
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
if (e instanceof SysException){
e = (SysException) e;
}else {
e = new SysException("该项功能正在维护中...");
}
ModelAndView view = new ModelAndView();
view.addObject("errorMsg",e.getMessage());
view.setViewName("error");
return view;
}
}
4.在spring配置文件中添加异常处理器的bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.source"></context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="sysException" class="cn.source.exception.SysExceptionResolver"></bean>
<mvc:annotation-driven/>
</beans>