开发者学堂课程【微服务+全栈在线教育实战项目演练(SpringCloud Alibaba+SpringBoot):统一异常处理】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/667/detail/11295
统一异常处理
内容简介:
一、全局异常处理
二、特殊异常处理
三、自定义异常处理
一、全局异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
//指定出现什么异常执行这个方法
@ExceptionHandler(Exception.class)
@ResponseBody//为了返回数据
public R error(Exception e) {
e.printStackTrace();
return R.error().message( "执行了全局异常处理.." );
二、特殊异常处理
//特定异常
@ExceptionHandler(ArithmeticException class)
@ResponseBody //为了返回教据
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message( "执行了 ArithmeticException 异常处理..");
}
查看结果,打开 swagger,
点击
/eduserice/teacher/pageTeacher/{current}/{limit}
current : 1
limit : 2
点击 try it out!
结果:
{
"suecess": false,
"code": 20001 ,
"message": "执行了 ArithmeticEeception 异常处理..",
"data": ()
}
三、自定义异常处理
第一步:创建自定义异常类继承 RuntimeException 写异常属性
@Data
@AllArgsConstructor //生成有参数构造方法
@NoArgsConstructor //生成无参数构造
public class GuliException extends RuntimeException {
private Integer code; //状态码
private String msg; //异常信息
}
第二步:在统一异常类添加规则
//自定义异常
@ExceptionHandler(GuliException.class)
@ResponseBody //为了返回数据
public R error(GuliException e) {
e.printStackTrace();
return R.error().code(e. getCode()).message(e. getMsg());
}
第三步:执行自定义异常
try{
int i= 10/0;
}catch(Exception e) {
//执行自定义异常
throw new GuliException(20001, "执行了自定义异常处理....");
}
打开 swagger
点击/eduserice/teacher/pageTeacher/{current}/{limit}
current : 1
limit : 2
点击 try it out!
结果:
{
"suecess": false,
"code": 20001 ,
"message": "执行了自定义异常处理....",
"data": ()
}
