加载中...

项目统一异常处理设计


全局异常处理

创建异常类,编写测试方法


@ControllerAdvice
public class GlobalExceptionHandler {

    @ApiOperation("全局异常处理") // 这样写会被挨打吗?
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        return Result.fail(null).message("执行了全局处理异常");
    }
    
}

编写测试controller


@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("findAll")
    public Result findAllTeacher() {
        List<Teacher> list = teacherService.list();
            int a = 10 / 0;
        return Result.ok(list).message("查询成功").code(200);
    }

}

特定异常处理

创建异常类,编写测试方法


@ControllerAdvice
public class GlobalExceptionHandler {

    @ApiOperation("特定异常处理") // 这样写会被挨打吗?
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e) {
        e.printStackTrace();
        return Result.fail(null).message("除数不能为0");
    }

}

编写测试controller


@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("findAll")
    public Result findAllTeacher() {
        List<Teacher> list = teacherService.list();
            int a = 10 / 0;
        return Result.ok(list).message("查询成功").code(200);
    }

}

自定义异常处理

创建自定义异常类


@Data
@AllArgsConstructor
@NoArgsConstructor
public class GgktException extends RuntimeException {
    private Integer code;
    private String msg;
}

编写自定义异常处理代码


@ControllerAdvice
public class GlobalExceptionHandler {

    @ApiOperation("自定义异常处理") // 这样写会被挨打吗?
    @ExceptionHandler(GgktException.class)
    @ResponseBody
    public Result error(GgktException e){
        e.printStackTrace();
        return Result.fail(null).message(e.getMsg()).code(e.getCode());
    }
    
}

编写测试controller


@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("findAll")
    public Result findAllTeacher() {
        List<Teacher> list = teacherService.list();
            int a = 10 / 0;
        return Result.ok(list).message("查询成功").code(200);
    }

}

成功


文章作者: shaoshaossm
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 shaoshaossm !
评论
  目录