SpringBoot异常处理五种方式

1.自定义错误页面

在resources/templates文件夹下新建error.html,出错后将跳转至该页面。
在这里插入图片描述

2.通过@ExceptionHandler注解处理异常

在异常出现的Controller中添加一个方法用@ExceptionHandler修饰

 @ExceptionHandler(value = {java.lang.NullPointerException.class})//valus参数设置异常的类型
    public ModelAndView nullPointerExceptionHandler(Exception e){//返回值是ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMsg",e.toString());//通过addObject()方法添加错误的信息
        modelAndView.setViewName("nullPointerExceptionView");//通过setViewName()方法设置返回视图的名称
        return modelAndView;
    }

在显示错误信息页面用thymeleaf表达式取出错误信息

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="${errorMsg}"></span>
</body>
</html>

3.通过@ControllerAdvice与@ExceptionHandler注解处理全局异常

新建类GlobalExceptionHandler.java用@ControllerAdvice修饰,在类中添加异常处理的方法

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {java.lang.NullPointerException.class})//valus参数设置异常的类型
    public ModelAndView nullPointerExceptionHandler(Exception e){//返回值是ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error",e.toString());//通过addObject()方法添加错误的信息
        modelAndView.setViewName("nullPointerExceptionView");//通过setViewName()方法设置返回视图的名称
        return modelAndView;
    }
}

4.通过SimpleMappingExceptionResolver对象处理异常

新建类GlobalExceptionHandler.java用@Configuration修饰,在类中添加异常处理的方法

@Configuration
public class GlobalExceptionHandler {
    /**
     * 此方法返回值必须是SimpleMappingExceptionResolver对象
     * @return SimpleMappingExceptionResolver
     */
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        /**
         * 参数一:异常类型的全名
         * 参数二:需要跳转的视图名称
         */
        properties.put("java.lang.NullPointerException","nullPointerError");
        resolver.setExceptionMappings(properties);
        return resolver;
    }

}

5.通过自定义HandlerExceptionResolver对象处理异常

@Configuration
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof NullPointerException){//判断产生的异常是哪种异常的实例
            modelAndView.setViewName("nullPointerExceptionView"); //通过setViewName()方法设置需要跳转的视图
        }
        modelAndView.addObject("errorMsg",e.toString());//通过addObject()方法传递异常的信息
        return modelAndView;
    }
}

你可能感兴趣的:(SpringBoot)