1、创建exception包
2、创建Exception类(自定义异常类) 并继承 RuntimeException
public class Exception extends RuntimeException {
/**
* 状态码
*/
private Integer code;
/**
* 错误信息
*/
private String msg;
/**
* 创建构造方法
*/
public Exception(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
//setter and getter方法省略......
}
3、创建异常处理类 CustomExceptionHa
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonData handler(Exception e) {
if (e instanceof Exception) {
Exception exception = (Exception) e;
return JsonData.buildError(exception.getCode(), exception.getMsg());
} else {
return JsonData.buildError("全局异常,位置错误!");
}
}
}
测试:
定义异常 int i = 1/0; 访问所在路径
@GetMapping("list_banner")
public JsonData indexBanner() {
List<Video> bannerList = videoService.listVideoBanner();
int i = 1/0;
return JsonData.buildSuccess(bannerList);
}