/** * 同余自定义异常基类 * <p>message.properties中定义 "消息key=value"</p> * * @author lQF */ @Data @JsonIgnoreProperties({"stackTrace", "localizedMessage", "suppressed"}) @EqualsAndHashCode(callSuper = true) public class TongyuBaseException extends RuntimeException { private static final String FILE_NAME = "message"; public static final int SERVICE_INTERNAL_ERROR_CODE = 500; public static final String SERVICE_INTERNAL_ERROR = "service internal error"; public static final Locale DEFAULT = Locale.getDefault(); /** * ResourceBundle bundle = ResourceBundle.getBundle("res", new Locale("zh", "CN")); * 其中new Locale(“zh”, “CN”)提供本地化信息,上面这行代码,程序会首先在classpath下寻找my_zh_CN.properties文件,若my_zh_CN.properties文件不存在,则取找my_zh.properties,如还是不存在,继续寻找my.properties,若都找不到就抛出异常。 */ private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(FILE_NAME, DEFAULT); /** * 带{0}占位的消息 */ private Object[] placeHolderArgs; /** * 错误码,复用 http status */ @JsonProperty("code") private int code; /** * 配置在message.properties的消息的key */ @JsonIgnore private String messageKey; public TongyuBaseException() { super(); defaultValue(); } /** * 指定错误码(同事也是消息key),如 "500=service internal error." * * @param code 错误码(如HTTP STATUS) */ public TongyuBaseException(int code) { this.code = code; this.messageKey = String.valueOf(code); } public TongyuBaseException(int code, Object... placeHolderArgs) { this.code = code; this.messageKey = String.valueOf(code); this.placeHolderArgs = placeHolderArgs; } /** * 指定错误码和消息key * * @param code 错误码(如HTTP STATUS) * @param messageKey 消息key */ public TongyuBaseException(int code, String messageKey) { this.code = code; this.messageKey = messageKey; } public TongyuBaseException(int code, String messageKey, Object... placeHolderArgs) { this.code = code; this.messageKey = messageKey; this.placeHolderArgs = placeHolderArgs; } private void defaultValue() { this.code = SERVICE_INTERNAL_ERROR_CODE; } @JsonProperty("error") @Override public String getMessage() { if (messageKey != null) { if (placeHolderArgs == null) { return BUNDLE.containsKey(messageKey) ? BUNDLE.getString(messageKey) : messageKey; } else { return messageFormat(placeHolderArgs); } } return super.getMessage(); } protected String messageFormat(Object[] args) { MessageFormat format = new MessageFormat(BUNDLE.getString(messageKey), DEFAULT); return format.format(args); } }