(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver:
<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--定义默认的异常处理页面,当该异常类型的注册时使用-->
<property name="defaultErrorView" value="error"></property>
<!--定义异常处理页面用来获取异常信息的变量名,默认名为exception-->
<property name="exceptionAttribute" value="ex"></property>
<!-- 定义需要特殊处理的异常,这是重要点 -->
<property name="exceptionMappings">
<props>
<!--key为异常类名,unauthorized为跳转页面-->
<prop key="org.apache.shiro.authz.AuthorizationException">unauthorized</prop>
<!-- 这里还可以继续扩展对不同异常类型的处理 -->
</props>
</property>
</bean>
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理。
@ControllerAdvice
public class BaseException {
@ExceptionHandler(ArithmeticException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> handleBusException(Exception e) {
Map<String, Object> map = new HashMap();
if (e instanceof MyException){
map.put("resCode","500");
map.put("message","myException");
}
if (e instanceof ArithmeticException){
map.put("resCode","500");
map.put("message","ArithmeticException");
}
return map;
}
@ControllerAdvice 全局的,该注解使@ExceptionHandler可以监控全局的异常
@ResponseStatus 指定返回状态码