本文章仅供小编学习使用,如有侵犯他人版权,请联系小编撤回或删除
GIt地址:https://github.com/mysupermans/CustomException-Rest.git
先看下目录结构
一、统一返回类型结构
为什么要统一格式?
我们使用SpringBoot编写接口的时候,最好是返回一个统一格式的JSON,该格式包含错误码,附带信息,以及携带的数据。这样前端在解析的时候就能统一解析,同时携带错误码可以更加容易的排查错误。
pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.7.RELEASE
com.example
log-demo
0.0.1-SNAPSHOT
log-demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.16.20
provided
com.alibaba
fastjson
1.2.47
org.apache.commons
commons-lang3
3.8.1
org.aspectj
aspectjrt
1.9.2
org.aspectj
aspectjweaver
1.9.2
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-maven-plugin
org.springframework.boot
spring-boot-maven-plugin
true
1、新建 BaseResponse 定义统一的系统基本返回类型
/**
* @program: workspace
* @description: 系统基本返回类型
* @author: 刘宗强
* @create: 2019-08-27 10:34
**/
public class BaseResponse {
private int code;
private String message;
private T data;
public BaseResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public BaseResponse(T data, ErrorType errorType){
this.code=errorType.getCode();
this.message=errorType.getMessage();
this.data=data;
}
public BaseResponse(ErrorType errorType){
this.code=errorType.getCode();
this.message=errorType.getMessage();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2、新建 BaseResponseBodyAdvice类 对restcontroller的body体进行统一返回
/**
* @program: workspace
* @description: 对restcontroller的body体进行统一返回
* @author: 刘宗强
* @create: 2019-08-27 16:59
**/
@ControllerAdvice
public class BaseResponseBodyAdvice implements ResponseBodyAdvice
3、新建 User 模型类 待会做测试用
/**
* @program: workspace
* @description:
* @author: 刘宗强
* @create: 2019-08-26 16:02
**/
@Data
@AllArgsConstructor
public class User {
private String userName;
@NotNull(message = "年龄不能为空!")
private Integer Age;
}
4、测试
/**
* @program: log-demo
* @description:
* @author: 刘宗强
* @create: 2019-08-26 12:02
**/
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
/**
* 测试Validated 后端参数校验
*/
@PostMapping("/addUser")
public User testPost(@RequestBody @Validated User user){
return user;
}
/**
* 返回对象信息
*/
@GetMapping("/getUser")
public User getUser(){
User user=new User("liuzongqiang",22);
return user;
}
/**
* 返回字符串
*/
@GetMapping("/getStr")
public String getStr(){
return "hello";
}
}
结果:
在返回string类型时报:
com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String
解决方案:https://www.jianshu.com/p/aacf72d6bf6f
配置一个消息转换器就可以了
二、统一异常处理
1、新建一个ErrorType 枚举类,用于定义系统错误类型
/**
* @program: workspace
* @description: 系统错误类型
* @author: 刘宗强
* @create: 2019-08-27 10:04
**/
public enum ErrorType {
//资源参数问题
PARAM_INVALID(-1, "参数不合法"),
NOT_FOUND(2, "不存在此资源"),
ALREADY_EXISTS(3, "资源已经存在,不能重复"),
PARAMS_NULL(3, "参数不能为空"),
//身份方面问题
REQUEST_OUT_OF_TIME(4, "请求过期"),
AUTHENTICATION_FAILED(100, "身份认证失败"),
REQUEST_METHOD_ERROR(101, "请求类型不支持"),
OPERATION_SCOPE_FAILED(102, "不支持此操作"),
//系统基本码
ERROR(0, "系统异常"),
SUCCESS(1, "成功");
private int code;
private String message;
ErrorType(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2、新建 CustomException 自定义异常类
/**
* @program: workspace
* @description: 用户自定义异常
* @author: 刘宗强
* @create: 2019-08-27 11:56
**/
public class CustomException {
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class ParamInvalidException extends RuntimeException{
private Map params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class NotFoundException extends RuntimeException{
private Map params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class AlreadyExistsException extends RuntimeException{
private Map params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class ParamNullException extends RuntimeException{
private Map params;
}
}
3、新建 BaseControllerAdvice 全局异常处理控制器
/**
* controller异常拦截,关键应用可从异常中获取有用信息并做日志记录
*/
@ControllerAdvice
public class BaseControllerAdvice {
@ResponseBody
@ExceptionHandler(Exception.class)
public BaseResponse sysError(Exception e){
return new BaseResponse<>(null,ErrorType.ERROR.getCode(),e.getMessage()==null?String.valueOf(e):ErrorType.ERROR.getMessage());
}
@ResponseBody
@ExceptionHandler(IllegalArgumentException.class)
public BaseResponse argumentError(IllegalArgumentException e){
return new BaseResponse<>(null,ErrorType.PARAM_INVALID.getCode(),e.getLocalizedMessage()==null?String.valueOf(e):e.getLocalizedMessage());
}
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseResponse validateException(MethodArgumentNotValidException e){
final List errList = new ArrayList<>();
e.getBindingResult().getAllErrors().stream().forEach(x-> {
errList.add(x.getDefaultMessage());
});
return new BaseResponse<>("",ErrorType.PARAM_INVALID.getCode(),errList.toString());
}
@ResponseBody
@ExceptionHandler(ParamInvalidException.class)
public BaseResponse> paramInvalidException(ParamInvalidException e){
return new BaseResponse<>(e.getParams(),ErrorType.PARAM_INVALID);
}
@ResponseBody
@ExceptionHandler(NotFoundException.class)
public BaseResponse> notFoundException(NotFoundException e){
return new BaseResponse<>(e.getParams(),ErrorType.NOT_FOUND);
}
@ResponseBody
@ExceptionHandler(AlreadyExistsException.class)
public BaseResponse> alreadyExistsException(AlreadyExistsException e){
return new BaseResponse<>(e.getParams(),ErrorType.ALREADY_EXISTS);
}
@ResponseBody
@ExceptionHandler(ParamNullException.class)
public BaseResponse> paramNullException(ParamNullException e){
return new BaseResponse<>(e.getParams(),ErrorType.PARAMS_NULL);
}
@ResponseBody
@ExceptionHandler(ImageUploadException.class)
public BaseResponse> imageUploadException(ImageUploadException e){
return new BaseResponse<>(e.getOriginFileUrl(),ErrorType.IMG_UPLOAD_ERR);
}
@ResponseBody
@ExceptionHandler(ImageNullException.class)
public BaseResponse> imageNullException(ImageNullException e){
return new BaseResponse<>(e.getParams(),ErrorType.IMG_NOT_NULL);
}
@ResponseBody
@ExceptionHandler(OssImageFailDelException.class)
public BaseResponse> ossImageFailDelException(OssImageFailDelException e){
return new BaseResponse<>(e.getParams(),ErrorType.OSS_FAIL_DEL);
}
@ResponseBody
@ExceptionHandler(InventoryUnEnoughException.class)
public BaseResponse> inventoryUnEnough(InventoryUnEnoughException e){
return new BaseResponse<>(e.getParams(),ErrorType.PRODUCT_INVENTORY_UNENOUGH);
}
}
4、测试
/**
* @program: log-demo
* @description:
* @author: 刘宗强
* @create: 2019-08-26 12:02
**/
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
@GetMapping("")
public String test(){
Map map=new HashMap<>();
map.put("id","12");
throw new CustomException.NotFoundException(map);
}
}
结果: