1. 基于配置文件的方式
1.配置springmvc.xml
SimpleMappingExceptionResolver对所有的异常进行统一的处理,将异常类名映射为视图名称。发生异常用自己自定义的视图名称将异常展示。
<prop key="异常类">视图名称</prop>
exceptionAttribute属性设置一个属性名ex,将出现的异常信息在请求域中进行共享
<property name="exceptionAttribute" value="ex"></property>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--
properties的键表示处理器方法执行过程中出现的异常,异常的全类名
properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--
exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
2. 测试控制类
@RequestMapping("/testException")
public String testException() {
int a = 10/0;
System.out.println(a);
return "error";
}
}
2. 基于注解的方式
@ControllerAdvice全局异常处理注解,相当于@Controller的增强版,本质上还是一个@Component,标注此注解的也会当作扫描组件
@ExceptionHandle 标注可发生的异常类
参数中设置Exception 获取异常信息
设置Model model向请求域中共享数据,传到前端页面。
//异常注解标注
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
public String testEx(Exception ex, Model model){
model.addAttribute("ex", ex);
return "error";
}
}