自定义异常处理演示

为了防止黑客从前台异常信息,对系统进行攻击。同时,为了提高用户体验,我们都会都抛出的异常进行拦截处理。

一、全局异常处理


编写一个异常拦截类,如下:@ControllerAdvice ,很多初学者可能都没有听说过这个注解,实际上,这是一个非常有用的注解,顾名思义,这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:①、全局异常处理;②、全局数据绑定;③、全局数据预处理;灵活使用这三个功能,可以帮助我们简化很多工作,需要注意的是,这是 SpringMVC 提供的功能,在 Spring Boot 中可以直接使用,下面分别来看。

 1 import com.edu.tools.R;
 2 import org.springframework.web.bind.annotation.ControllerAdvice;
 3 import org.springframework.web.bind.annotation.ExceptionHandler;
 4 import org.springframework.web.bind.annotation.ResponseBody;
 5 
 6 /**
 7  * @description:
 8  * @author: zzx
 9  * @createDate: 2020/6/2
10  * @version: 1.0
11  */
12 @ControllerAdvice
13 public class GlobalExceptionHandler {
14 
15     //很重要,括号类制定需要拦截的异常,也可以进行定制化
16     @ExceptionHandler(Exception.class)
17     @ResponseBody
18     public R error(Exception e){
19         e.printStackTrace();
20         //R表示我们给前端返回的接口格式
21         return R.error().message("执行全局异常处理。。。");
22     }
23 }

二、全局异常处理测试


三、自定义异常处理


【1】创建自定义异常类继承 RuntimeException类。

 1 /**
 2  * @description: 自定义异常类,包含了有参合无参构造器
 3  * @author: zzx
 4  * @createDate: 2020/6/2
 5  * @version: 1.0
 6  */
 7 @Data
 8 @AllArgsConstructor
 9 @NoArgsConstructor
10 public class BusinessException extends RuntimeException {
11     private Integer code;//状态码
12     private String msg;//异常消息
13 }

【2】将自定义的异常类添加到拦截的 Handler 中

 1 /**
 2  * @description:
 3  * @author: zzx
 4  * @createDate: 2020/6/2
 5  * @version: 1.0
 6  */
 7 @ControllerAdvice
 8 public class GlobalExceptionHandler {
 9 
10     //拦截自定义异常
11     @ExceptionHandler(BusinessException .class)
12     @ResponseBody
13     public R error(BusinessException e){
14         e.printStackTrace();
15         return R.error().code(e.getCode()).message(e.getMsg());
16     }
17 }

【3】在业务代码根据需求进行手动抛出即可,业务代码展示:throw new BusinessException(20001,"手动异常抛出");

 1 /**
 2  * <p>
 3  * 讲师 前端控制器
 4  * </p>
 5  *
 6  * @author zhengzhaoxiang
 7  * @since 2020-06-01
 8  */
 9 @RestController
10 @RequestMapping("/eduservice/edu-teacher")
11 public class EduTeacherController {
12     @Autowired
13     private EduTeacherService eduTeacherService;
14 
15     /**
16     * @Description 获取所有数据
17     * @Author zhengzhaoxiang
18     * @Date 2020/6/2 15:27
19     * @Param []
20     * @Return void
21     */
22     @GetMapping("findAll")
23     public R findAll(){
24 
25         List<EduTeacher> list = eduTeacherService.list(null);
26         try{
27             int i = 1/0;
28         } catch (Exception e){    
29             //手动抛出异常
30             throw new BusinessException(20001,"手动异常抛出");
31         }
32 
33         return R.ok().data("items",list);
34     }
35 }

四、自定义异常处理测试


posted @ 2020-11-15 00:26  Java程序员进阶  阅读(10)  评论(0编辑  收藏  举报