/**
* 统一异常处理类
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e){
e.printStackTrace();
return R.error();
}
}
二、特定异常处理
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
4
e.printStackTrace();
5
return R.error().message("执行了自定义异常");
6
}
三、自定义异常处理
一,创建自定义异常类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException {
@ApiModelProperty(value = "状态码")
private Integer code;
private String msg;
}
二、业务中需要的位置抛出GuliException
try {
int a = 10/0;
}catch(Exception e) {
throw new GuliException(20001,"出现自定义异常");
}
三、添加异常处理方法
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}