目录

一、单个控制器异常处理

二、全局异常处理器

三、自定义异常处理器


一、单个控制器异常处理

@RequestMapping("/t2")
@Controller
public class MyController2 {

    @RequestMapping("/c1")
    public String t1(){
        String str=null;
        str.length();
        return "main";
    }
    @RequestMapping("/c2")
    public String t2(){
        int i=1/0;
        return "main";
    }
    @RequestMapping("/c3")
    public String t3(){
        int[] a=new int[1];
        a[2]=1;
        return "main";
    }
    @ExceptionHandler({java.lang.NullPointerException.class})
    public String exce1(Exception e, Model model){
        //向模型中添加异常对象
        model.addAttribute("msg",e);
        return "error";
    }
    //方法1处理不了的异常交给2处理
    @ExceptionHandler(java.lang.Exception.class)
    public String ex2(Exception e,Model model){
        model.addAttribute("msg",e);
        return "error";
    }
}

二、全局异常处理器

//全局异常处理器类,需要添加@ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(java.lang.NullPointerException.class)
    public String exception1(Exception e, Model model){
        model.addAttribute("msg",e);
        return "error";
    }
    //方法一捕捉不到的交给2
    @ExceptionHandler(java.lang.Exception.class)
    public String exception2(Exception e,Model model){
        model.addAttribute("msg",e);
        return "error1";
    }
}

三、自定义异常处理器

//自定义异常处理器需要实现HandlerExceptionResolver接口,并放入Spring容器中
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView=new ModelAndView();
        if(ex instanceof NullPointerException){
            //空指针异常
            modelAndView.setViewName("error");
        }
        else{
            modelAndView.setViewName("error1");
        }
        modelAndView.addObject("msg",ex);
        return modelAndView;
    }
}
04-29 08:17