SpringMvc中的异常处理器(在SpringBoot中也可使用)

发布于:2024-04-29 ⋅ 阅读:(24) ⋅ 点赞:(0)

目录

一、单个控制器异常处理

二、全局异常处理器

三、自定义异常处理器


在开发过程中,Dao,service,Controller层代码出现异常都可能抛出异常。如果哪里产生异常就在哪里处理异常,则会降低开发效率。所以一般情况下我们会让异常向上抛出,最终到达DispatcherServlet中,此时SpringMvc提供了异常处理器进行异常处理,这样可以提高开发效率。

一、单个控制器异常处理

@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";
    }
}

三、自定义异常处理器

以上都是SpringMvc自带的异常处理器进行异常处理,我们也可以通过自定义异常处理器进行异常处理

//自定义异常处理器需要实现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;
    }
}