1.编写一个类,实现handlerexceptionresolver接口

@component
public class exceptionresolver implements handlerexceptionresolver {

    @override
    public modelandview resolveexception(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o, exception e) {

        system.out.println("异常处理器正在执行中");

        modelandview mv = new modelandview();
        if (e instanceof nullpointerexception){
            mv.addobject("msg","空指针异常");
        }else if (e instanceof accessdeniedexception){
            mv.addobject("msg","没有访问权限");

            system.out.println("111---222---333");
        }

        mv.setviewname("/error.html");
        return mv;
    }

}

步骤2:在类上添加@component注解,将类放入容器中。

或者在配置文件中声明该类的bean标签

<bean class="com.itheima.exception.myexceptionresolver"></bean>

1.异常处理 实现handlerexceptionresolver接口 同一处理所有异常,需要手动细分异常 返回类型被限定为modelandview

2.自定义类,类上加注解@controlleradvice

@controlleradvice:声明该类是一个controller的通知类,声明后该类就会被加载成异常处理器

//声明该类是一个controller的通知类,声明后该类就会被加载成异常处理器
@controlleradvice
public class exceptionadvice {

    //类中定义的方法携带@exceptionhandler注解的会被作为异常处理器,后面添加实际处理的异常类型
    @exceptionhandler(nullpointerexception.class)
    @responsebody
    public string donullexception(exception ex) {
        return "空指针异常";
    }
	//算术异常
    @exceptionhandler(arithmeticexception.class)
    @responsebody
    public string doarithmeticexception(exception ex) {
        return "arithmeticexception";
    }

    @exceptionhandler(exception.class)
    @responsebody
    public string doexception(exception ex) {
        return "all";
    }
}

两种异常处理的区别:

1.第二种注解异常处理可以处理 handler 方法参数出现异常的情况,而第一种处理不了。

2.第二种注解异常处理对结果更加灵活,可以返回modelandview、string、对象等。

总结

到此这篇关于spring框架中异常处理情况的文章就介绍到这了,更多相关spring异常处理情况内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!