发布于 

全局错误码国际化。枚举中注入bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
public enum ResultCode {

/**
*
*/
SUCCESS(20000, "成功"),
ERROR(20001, "服务器内部错误"),
EMPTY_PARAM(20003, "非空参数需要传递"),
BAD_PARAM(20004, "参数错误"),

USER_REGISTER_PARAMS_REPEAT(10001, "用户注册信息重复"),
USER_NOT_LOGIN(10002, "用户未登录"),
USER_NOT_EXIST(10003, "用户手机号未注册"),
USER_LOCKED(10004, "账号已被锁定,联系管理员"),

USER_CHAT_LIMITED(30001, "用户当日聊天功能已达到上限!"),
USER_FILE_UPLOAD_LIMITED(30002, "用户当日文件上传功能已达到上限!"),


ADMIN_OPERATE_FORBIDDEN(40001, "禁止操作管理员权限的功能!"),
ADMIN_APIKEY_NULL(40002, "系统API-Key使用繁忙!请稍后再试~"),

UPLOAD_FILE_ERROR(50001, "文件处理失败,请检查文件页数!"),


;

public final int code;
public final String msg;

public String getMsg() {
String message = "";
try {
message = ReportTypeServiceInjector.messageSource.getMessage(code + "", null, LocaleContextHolder.getLocale());
} catch (Exception e) {
log.error("{}的国际化错误信息未添加或出错.", code);

}
if (!Strings.isNullOrEmpty(message))
return message;
return msg;
}

ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}


@Component
public static class ReportTypeServiceInjector {

@Resource
private MessageSource messagSource;

private static MessageSource messageSource;

@PostConstruct
private void postConstruct() {
ReportTypeServiceInjector.messageSource = messagSource;
}

}

}

application.properties中,配置了2个国际化语言包
spring.messages.basename= i18n.messages,i18n.errors

其他地方调用

1
throw new BaseException(ResultCode.ADMIN_APIKEY_NULL.getMsg());