SpringMVC全局异常统一处理

(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 指定返回状态码



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值