1.异常类设计
CommonException类
@Data
public class CommonException extends RuntimeException{
private MessageKey messageKey;
public CommonException(MessageKey messageKey,String message){
super(message);
this.messageKey = messageKey;
}
}
MessageKey接口,该接口定义异常信息key类的方法
public interface MessageKey {
String getKey();
int getCode();
}
UserMessageKey:MessageKey的实现类
public enum UserMessageKey implements MessageKey{
USER_NAME_ERROR("USER_NAME_ERROR",1000),
USER_PASSWORD_ERROR("USER_PASSWORD_ERROR",1001),
LOGIN_SUCCESS("LOGIN_SUCESS",1005);
private Integer code;
private String key;
UserMessageKey(String key,Integer code){
this.code = code;
this.key = key;
}
@Override
public String getKey() {
return this.key;
}
@Override
public int getCode() {
return this.code;
}
}
使用demo
messageSource.getMessage(UserMessageKey.USER_NAME_ERROR.getKey(),null,UserMessageKey.USER_NAME_ERROR.getKey()
在messageSource配置表中增加USER_NAME_ERROR对应的各种语言value
UserException用户异常类,继承CommonException
public class UserException extends CommonException{
public UserException(MessageKey messageKey, String message) {
super(messageKey, message);
}
}
2.Response类设计
@Data
public class CommonResponse<T> {
private Integer code;
private Boolean success;
private String message;
private T data;
//默认结果
public CommonResponse(){
this.code = 200;
this.success = true;
}
//返回数据但没有提示信息
public static <T> CommonResponse of(T data) {
CommonResponse commonResponse = new CommonResponse();
commonResponse.setData(data);
return commonResponse;
}
//返回数据带提示信息
public static <T> CommonResponse of(T data,String message){
CommonResponse commonResponse = new CommonResponse();
commonResponse.setData(data);
commonResponse.setMessage(message);
return commonResponse;
}
//错误信息提示,message为提示信息,code为返回异常状态值
public static <T> CommonResponse of(String message,Integer code){
CommonResponse commonResponse = new CommonResponse();
commonResponse.setMessage(message);
commonResponse.setCode(code);
commonResponse.setSuccess(false);
return commonResponse;
}
}