先整体看下代码结构:
返回结果封装类RestResult:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RestResult {
private Integer code;
private String message;
private Object data;
public static RestResult of(Object data) {
return new RestResult(0, "success", data);
}
public static RestResult of(Exception e) {
if (e instanceof BusinessException) {
return new RestResult(((BusinessException) e).getCodeId(), e.getMessage(), ((BusinessException) e).getErrors());
} else {
return new RestResult(500, e.getMessage(), Collections.emptyMap());
}
}
public static RestResult of(Exception e, Integer code) {
if (e instanceof BusinessException) {
return new RestResult(((BusinessException) e).getCodeId(), e.getMessage(), ((BusinessException) e).getErrors());
} else {
return new RestResult(code, e.getMessage(), Collections.emptyMap());
}
}
}
统一异常封装类:
/**
* @description: 对于需要给用户展示的异常,统一抛出此异常
* @author: JJC
* @createTime: 2019/3/28
*/
public class BusinessException extends RuntimeException implements Serializable {
private final ErrorCode code;
private final Map<String, ? extends Object> errors;
public BusinessException(ErrorCode code, Map<String, Object> errors) {
super(code.getReason());
this.code