一、什么是统一异常处理
1、制造异常
除以0
int a = 10/0;
2、什么是统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理
二、统一异常处理
1、添加依赖
service-base模板中引入common_utils依赖
<dependency><groupId>com.atguigu</groupId><artifactId>common_utils</artifactId><version>0.0.1-SNAPSHOT</version></dependency>
2、创建统一异常处理器
在service-base中创建统一异常处理类GlobalExceptionHandler.java:
package com.atguigu.servicebase.exceptionhandler;/*** 统一异常处理类*/@ControllerAdvicepublic class GlobalExceptionHandler {//指定出现什么异常执行这个方法@ExceptionHandler(Exception.class)@ResponseBodypublic R error(Exception e){e.printStackTrace();return R.error().message(e.getMessage());}}
2、测试
三、处理特定异常
1、添加异常处理方法
GlobalExceptionHandler.java中添加
package com.atguigu.servicebase.exceptionhandler;/*** 统一异常处理类*/@ControllerAdvicepublic class GlobalExceptionHandler {//特定异常@ExceptionHandler(ArithmeticException.class)@ResponseBodypublic R error(ArithmeticException e){e.printStackTrace();return R.error().message("执行了ArithmeticException异常处理..");}}
2、测试
四、自定义异常
1、创建自定义异常类
package com.atguigu.servicebase.exceptionhandler;@Data@AllArgsConstructor //生成有参数构造方法@NoArgsConstructor //生成无参数构造public class GuliException extends RuntimeException {private Integer code;//状态码private String msg;//异常信息}
2、业务中需要的位置抛出GuliException
package com.atguigu.eduservice.controller;@Api(description="讲师管理")@RestController@RequestMapping("/eduservice/teacher")public class EduTeacherController {@Autowiredprivate EduTeacherService teacherService;//3 分页查询讲师的方法@GetMapping("pageTeacher/{current}/{limit}")public R pageListTeacher(@PathVariable long current,@PathVariable long limit) {//创建page对象Page<EduTeacher> pageTeacher = new Page<>(current,limit);try {int i = 10/0;}catch(Exception e) {//执行自定义异常throw new GuliException(20001,"执行了自定义异常处理....");}//调用方法实现分页teacherService.page(pageTeacher,null);long total = pageTeacher.getTotal();//总记录数List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合return R.ok().data("total",total).data("rows",records);}}
3、添加异常处理方法
GlobalExceptionHandler.java中添加
package com.atguigu.servicebase.exceptionhandler;/*** 统一异常处理类*/@ControllerAdvicepublic class GlobalExceptionHandler {//自定义异常@ExceptionHandler(GuliException.class)@ResponseBody //为了返回数据public R error(GuliException e) {log.error(e.getMessage());e.printStackTrace();return R.error().code(e.getCode()).message(e.getMsg()); //注意:不是e.getMessage()}}
4、测试


