在线教育项目-day02【异常处理】

1.在servicebase中创建统一异常处理器

新建包如图:

@ControllerAdvice
public class GlocalExceptionhHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.Error().message("执行了全局异常处理。。。");
    }
}

2.导入依赖:

 然后这里我们要注意一个依赖传递,就是servicebase会包含common_utils

 

 

3.自定义异常处理

实际项目中我们都要自定义异常,总不能全用一个统一的信息显示错误信息。

其实我们还可以把

@ExceptionHandler(Exception.class)
这个注解更改,改成特定的异常,输出特定的信息,但是这样太浪费时间了,况且不知道实际情况会出现什么异常

我们新建一个类继承RuntimeException

@Data
@AllArgsConstructor//生成有参数的构造方法
@NoArgsConstructor//生成无参数的构造方法
public class onlineEduException extends RuntimeException {
    private Integer code;
    private String msg;


}

在刚才创建的GlobalExceptionHandler.java中添加

    //自定义异常
    @ExceptionHandler(onlineEduException.class)
    @ResponseBody
    public R error(onlineEduException e){
        e.printStackTrace();
        return R.Error().message(e.getMsg()).code(e.getCode());
    }

接下来我们去执行一个自定义异常

 

原文地址:https://www.cnblogs.com/dmzna/p/12795191.html