springmvc学习之异常处理器

1.异常种类
有两种异常:1)预期异常
2)运行时异常
springmvc提供一个全局异常处理器(一个系统只有一个)进行统一异常处理
2. 自定义异常类
根据预期的异常,在程序中抛出此系统自定义的异常
这个类用来表示是不是系统自定的异常

```
public class CustomException extends Exception{
    public String message; //定义异常信息
   public CustomException(String  message) {
          super(message);
          this.message = message;
          }
    public String getMessge(){
             return message;}
public String setMessage(String message) {
           this.message = message;
           }
构造函数进行赋值,也可以继承父类的构造函数来,使用super(message);

3.全局异常处理器
思路:系统遇到异常,在程序中手动抛出,dao抛给service,service抛给controller,controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:
解析出异常类型,如果该异常类型是系统自定义的异常,直接取出异常信息在页面进行展示,如果不是则构造一个异常信息(信息为“未知错误”)
全局异常处理器:实现HandlerexceptionResolver接口,在springmvc中配置全局异常处理器,不用id,直接实现上面的接口就可以了,

 <bean class="自己写的类的全限定名"> </bean>
public class CustomExceptionTest implement  HandlerexceptionResolver {
        @Override
        public  ModelAndView resolveException(HttpServletRequest request ,HttpServletResponse response ,Object handler, Exception ex) {//handler就是处理器适配器Handler对象,只有method
        CustomException customException = new CustomException();
        //如果是ex系统自定义的异常,就强转为自己定义的异常类,如果不是就输出位置错误;
        if(ex instanceof customException ) {
        customException =(customException )ex;
        }else{
        customException = new CustomException("未知错误");
       } 
        String message = customException.getMessage;
        //创建ModelAndView 添加message到页面,并指向要跳转的页面
        ModelAndView  modelAndView = new ModelAndView();
        modelAndView.addObject("message",message);
        modelAndView.setViewName("error");
        return modelAndView;
        }
}

4.异常测试
在controller,service,dao任一层手动抛出能使用的自己写的异常信息,如果不是手动抛出异常,说明是一个运行时错误显示未知错误 。
如:

 if(item == null ){
          throw new CustomException("修改的商品信息不存在");
          }

PS: 与业务无关的建议在controller层抛出,有关的建议在service层抛出,service层能抛出是因为业务层函数有throw Exception, throw Exception表示抛出让上层来处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值