diff --git a/src/main/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandler.java b/src/main/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandler.java new file mode 100644 index 0000000..ad17f2c --- /dev/null +++ b/src/main/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandler.java @@ -0,0 +1,459 @@ +package com.eactive.eai.adapter.handler; + +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import com.eactive.eai.common.message.EAIMessage; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.JacksonUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.MessageUtil; +import com.eactive.eai.message.StandardMessage; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * API 별로 오류 응답 구조가 다른 기관용 템플릿 핸들러. + * + *
{@link TemplateAdapterErrorMsgHandler} 가 어댑터 그룹 단위로 템플릿 하나를 쓰는 것과 달리, + * 같은 어댑터 그룹 안에서 API ID 별로 템플릿을 고르고, 요청 배열을 그대로 에코한 + * 배열 응답을 만들 수 있다. 응답코드/응답메시지는 표준전문 오류코드를 매핑해 채운다. + * + *
기관이 늘어도 클래스를 만들지 않는다. 어댑터 프로퍼티의 ERR_MSG_HANDLER 에
+ * 이 클래스를 그대로 지정하고, 프로퍼티 그룹 ERR{어댑터그룹명} 만 만들면 된다.
+ * 기관 고유 로직이 필요할 때만 상속해서 {@link #getPropGroup(String)} 등을 오버라이드한다.
+ *
+ *
[동작] + *
+ * 1. 표준전문 오류코드 추출
+ * 2. 코드/메시지 매핑 결과 산출 → ${rslt_cd}, ${rslt_msg}
+ * 3. API ID(= api.key 로 지정한 callProp 값, 기본 API_SERVICE_CODE) 로 템플릿 선택
+ * 4. 배열 API 면 요청 배열을 돌며 item 템플릿을 렌더해 배열 조립 → ${array}
+ * 5. 본문 템플릿 렌더
+ *
+ *
+ * [템플릿에서 쓰는 값] + *
+ * ${rslt_cd} 매핑된 응답코드
+ * ${rslt_msg} 매핑된 응답메시지
+ * ${item.필드} 배열 요소의 값 (array.item 템플릿 전용)
+ * ${array} 조립이 끝난 배열 (겉 템플릿, 따옴표 없이)
+ * ${callprop.INBOUND_REQUEST_MESSAGE.필드} 요청 전문의 값
+ *
+ * 내부 키 표기 ${callprop.TPL_RSLT_CD}, ${callprop.TPL_RSLT_MSG},
+ * ${callprop.TPL_ITEM.필드}, ${callprop.TPL_ARRAY} 도 동작한다.
+ *
+ *
+ * api.key = API_SERVICE_CODE API ID 로 쓸 callProp 키 (기본값)
+ *
+ * {apiId}.template = {"rows":${array}}
+ * {apiId}.array.source = rows 요청 배열 경로 (dot 경로 가능)
+ * {apiId}.array.item = {"no":"${item.no}","rslt_cd":"${rslt_cd}"}
+ * {apiId}.sys.template / {apiId}.in.template 경로별로 다르게 낼 때만 등록
+ * (없으면 {apiId}.template 을 그대로 쓴다)
+ *
+ * rslt_cd.40000 = CP4000 응답코드 매핑
+ * rslt_cd.default = CP5000
+ * rslt_msg.40000 = 형식 오류입니다 응답메시지 매핑
+ * rslt_msg.default = 시스템 오류입니다
+ *
+ * err.code.path = MSG.MAIN_MSG.outp_msg_cd 표준전문 오류코드 경로 (기본값)
+ *
+ * template / sys.template / in.template API ID 별 템플릿이 없을 때 공통 폴백
+ *
+ */
+public class ApiTemplateAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
+
+ private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
+
+ /**
+ * 어댑터 그룹 전용 프로퍼티 그룹 이름 형식 : ERR{어댑터그룹명}
+ * 어댑터 그룹명이 길어 그룹명 길이 제한에 걸리지 않도록 접두어를 짧게 둔다.
+ */
+ public static final String PROP_GROUP_PREFIX = "ERR{";
+ public static final String PROP_GROUP_SUFFIX = "}";
+ /** 어댑터 그룹 전용 프로퍼티 그룹이 없을 때 쓰는 기본 그룹 */
+ public static final String DEFAULT_PROP_GROUP = "ERR{API}";
+
+ /** API ID 로 사용할 callProp 키를 지정하는 설정 키 */
+ static final String KEY_API_KEY = "api.key";
+ /** 응답코드 매핑 접두어 */
+ static final String KEY_RSLT_CD_PREFIX = "rslt_cd.";
+ /** 응답메시지 매핑 접두어 */
+ static final String KEY_RSLT_MSG_PREFIX = "rslt_msg.";
+ /** 표준전문 오류코드 경로를 바꿀 때 쓰는 설정 키 */
+ static final String KEY_ERR_CODE_PATH = "err.code.path";
+ /** 매핑 폴백 접미어 */
+ static final String KEY_DEFAULT_SUFFIX = "default";
+ /** 배열 설정 접미어 */
+ static final String KEY_ARRAY_SOURCE = "array.source";
+ static final String KEY_ARRAY_ITEM = "array.item";
+
+ static final String DEFAULT_API_KEY = "API_SERVICE_CODE";
+ static final String DEFAULT_ERR_CODE_PATH = "MSG.MAIN_MSG.outp_msg_cd";
+
+ /** 템플릿 별칭 토큰 */
+ static final String ALIAS_RSLT_CD = "${rslt_cd}";
+ static final String ALIAS_RSLT_MSG = "${rslt_msg}";
+ static final String ALIAS_ARRAY = "${array}";
+ private static final String ALIAS_ITEM_MARK = "${item.";
+ private static final Pattern ALIAS_ITEM_PATTERN = Pattern.compile("\\$\\{item\\.([^}]+)\\}");
+
+ /** 렌더 중 callProp 에 임시로 주입하는 키 */
+ static final String CP_RSLT_CD = "TPL_RSLT_CD";
+ static final String CP_RSLT_MSG = "TPL_RSLT_MSG";
+ static final String CP_ITEM = "TPL_ITEM";
+ static final String CP_ARRAY = "TPL_ARRAY";
+
+ /** 인바운드 필터 오류 시 컨트롤러가 넣어주는 GW 오류코드 */
+ static final String CP_INBOUND_RESULT_CODE = "INBOUND_RESULT_CODE";
+ /** 어댑터가 저장해 둔 요청 전문 원본 */
+ static final String CP_INBOUND_REQUEST_MESSAGE = "INBOUND_REQUEST_MESSAGE";
+
+ /** 기본 ObjectMapper 는 선행 0 / 큰 수를 훼손한다. */
+ private static final ObjectMapper OBJECT_MAPPER = JacksonUtil.newNumberSafeMapper();
+
+ /**
+ * 설정을 읽어올 프로퍼티 그룹을 정한다.
+ *
+ * 1. ERR{어댑터그룹명} 해당 그룹이 등록되어 있으면 사용
+ * 2. ERR{API} 없으면 전역 기본 그룹
+ *
+ * 기관마다 클래스를 만들 필요 없이 프로퍼티 그룹만 추가하면 된다.
+ * 기관 고유 로직이 필요할 때만 상속해서 오버라이드한다.
+ */
+ protected String getPropGroup(String adapterGroupName) {
+
+ if (StringUtils.isNotBlank(adapterGroupName)) {
+ String group = PROP_GROUP_PREFIX + adapterGroupName + PROP_GROUP_SUFFIX;
+ if (hasPropGroup(group)) {
+ return group;
+ }
+ }
+ return DEFAULT_PROP_GROUP;
+ }
+
+ /** 프로퍼티 그룹이 등록되어 있고 비어 있지 않은지 확인한다. */
+ protected boolean hasPropGroup(String group) {
+ Properties props = PropManager.getInstance().getProperties(group);
+ return props != null && !props.isEmpty();
+ }
+
+ // ================================================================
+ // AdapterErrorMessageHandler 구현
+ // ================================================================
+
+ /** 업무시스템 오류 응답 */
+ @Override
+ public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName,
+ String inboundAdapterName, Properties callProp, Object outboundRequestData,
+ EAIMessage resEaiMsg) throws Exception {
+
+ String group = getPropGroup(inboundAdapterGroupName);
+ StandardMessage stdMsg = (resEaiMsg != null) ? resEaiMsg.getStandardMessage() : null;
+ return build(group, callProp, stdMsg, null,
+ resolveErrorCode(group, stdMsg, resEaiMsg, callProp), "");
+ }
+
+ /** GW 내부 오류 응답 */
+ @Override
+ public Object generateNonStandardInternalErrorResponseMessage(String inboundAdapterGroupName,
+ String inboundAdapterName, Properties callProp, Object inboundRequestData,
+ EAIMessage resEaiMsg) throws Exception {
+
+ String group = getPropGroup(inboundAdapterGroupName);
+ StandardMessage stdMsg = (resEaiMsg != null) ? resEaiMsg.getStandardMessage() : null;
+ return build(group, callProp, stdMsg, null,
+ resolveErrorCode(group, stdMsg, resEaiMsg, callProp), "sys.");
+ }
+
+ /** 인바운드 필터 오류 응답 (StandardMessage 없음) */
+ @Override
+ public Object generateNonStandardInboundErrorResponseMessage(String adapterGroupName,
+ String adapterName, Properties callProp, Object inboundRequestData,
+ Object inboundResponseData, Throwable e) throws Exception {
+
+ String group = getPropGroup(adapterGroupName);
+ return build(group, callProp, null, e, resolveErrorCode(group, null, null, callProp), "in.");
+ }
+
+ // ================================================================
+ // 공통 처리
+ // ================================================================
+
+ /**
+ * 코드/메시지 산출 → 템플릿 선택 → 배열 조립 → 본문 렌더.
+ *
+ * @param templateInfix 템플릿 키 중간 구분자 ("" / "sys." / "in.")
+ * @return 렌더된 본문. 템플릿이 없으면 null (상위에서 기본 오류 응답으로 폴백)
+ */
+ private String build(String group, Properties callProp, StandardMessage stdMsg, Throwable exception,
+ String errorCode, String templateInfix) {
+
+ Properties prop = (callProp != null) ? callProp : new Properties();
+
+ String apiId = resolveApiId(group, prop);
+ String template = findTemplate(group, apiId, templateInfix);
+ if (StringUtils.isBlank(template)) {
+ if (logger.isWarn()) {
+ logger.warn("ApiTemplateAdapterErrorMsgHandler] template not found. group=" + group
+ + ", apiId=" + apiId + ", infix=" + templateInfix);
+ }
+ return null;
+ }
+
+ try {
+ String rsltCd = mapValue(group, KEY_RSLT_CD_PREFIX, errorCode);
+ String rsltMsg = mapValue(group, KEY_RSLT_MSG_PREFIX, errorCode);
+
+ // ${callprop.TPL_RSLT_CD} 표기로도 참조할 수 있게 callProp 에 넣어둔다
+ prop.setProperty(CP_RSLT_CD, rsltCd);
+ prop.setProperty(CP_RSLT_MSG, rsltMsg);
+
+ String arrayJson = buildArray(group, apiId, prop, stdMsg, exception, rsltCd, rsltMsg);
+ if (arrayJson != null) {
+ prop.setProperty(CP_ARRAY, arrayJson);
+ }
+
+ return render(applyAliases(template, rsltCd, rsltMsg, null, arrayJson),
+ stdMsg, prop, exception);
+ } catch (Exception e) {
+ logger.error("ApiTemplateAdapterErrorMsgHandler] build fail - " + e.getMessage(), e);
+ return null;
+ } finally {
+ // 거래 Properties 를 그대로 쓰므로 임시 키는 반드시 걷어낸다 (로깅에 섞이는 것 방지)
+ prop.remove(CP_RSLT_CD);
+ prop.remove(CP_RSLT_MSG);
+ prop.remove(CP_ARRAY);
+ prop.remove(CP_ITEM);
+ }
+ }
+
+ /**
+ * 요청 배열을 돌며 item 템플릿을 렌더해 JSON 배열 문자열을 만든다.
+ * 배열 설정이 없으면 null.
+ * 요청 배열이 없거나 파싱 실패면 에코 없이 1건만 만들어 오류코드를 전달한다.
+ */
+ private String buildArray(String group, String apiId, Properties prop, StandardMessage stdMsg,
+ Throwable exception, String rsltCd, String rsltMsg) {
+
+ String sourcePath = getApiProp(group, apiId, KEY_ARRAY_SOURCE);
+ String itemTemplate = getApiProp(group, apiId, KEY_ARRAY_ITEM);
+ if (StringUtils.isBlank(sourcePath) || StringUtils.isBlank(itemTemplate)) {
+ return null; // 배열 API 가 아니다
+ }
+
+ JsonNode sourceArray = readRequestArray(prop, sourcePath);
+ if (sourceArray == null || !sourceArray.isArray() || sourceArray.size() == 0) {
+ // 요청 전문이 비정상이거나 배열이 비었어도 오류코드는 전달되어야 한다.
+ // 배열 요소 안에만 응답코드 자리가 있는 전문(카카오뱅크 등)에서 빈 배열로 내보내면
+ // 수신측이 오류 내용을 알 수 없으므로, 에코 필드는 빈 값으로 두고 1건을 만든다.
+ if (logger.isWarn()) {
+ logger.warn("ApiTemplateAdapterErrorMsgHandler] request array not found. path=" + sourcePath
+ + " - 에코 없이 1건으로 응답한다");
+ }
+ return "[" + render(applyAliases(itemTemplate, rsltCd, rsltMsg, null, null),
+ stdMsg, prop, exception) + "]";
+ }
+
+ StringBuilder sb = new StringBuilder("[");
+ for (int i = 0; i < sourceArray.size(); i++) {
+ JsonNode item = sourceArray.get(i);
+
+ // ${callprop.TPL_ITEM.필드} 표기로도 참조할 수 있게 callProp 에 실어둔다
+ prop.setProperty(CP_ITEM, item.toString());
+
+ if (i > 0) {
+ sb.append(",");
+ }
+ sb.append(render(applyAliases(itemTemplate, rsltCd, rsltMsg, item, null),
+ stdMsg, prop, exception));
+ }
+ prop.remove(CP_ITEM);
+
+ return sb.append("]").toString();
+ }
+
+ /**
+ * 템플릿의 별칭 토큰을 렌더 전에 치환한다.
+ *
+ * ${rslt_cd} / ${rslt_msg} → 매핑 결과
+ * ${array} → 조립한 배열 (null 이면 빈 문자열)
+ * ${item.경로} → 현재 배열 요소의 값 (item 이 null 이면 빈 문자열)
+ *
+ * 치환값의 제어문자는 render 와 동일한 이유로 제거한다.
+ */
+ private String applyAliases(String template, String rsltCd, String rsltMsg,
+ JsonNode item, String arrayJson) {
+
+ String result = template
+ .replace(ALIAS_RSLT_CD, MessageUtil.stripControlChars(StringUtils.defaultString(rsltCd)))
+ .replace(ALIAS_RSLT_MSG, MessageUtil.stripControlChars(StringUtils.defaultString(rsltMsg)))
+ .replace(ALIAS_ARRAY, StringUtils.defaultString(arrayJson));
+
+ if (!result.contains(ALIAS_ITEM_MARK)) {
+ return result;
+ }
+
+ Matcher matcher = ALIAS_ITEM_PATTERN.matcher(result);
+ StringBuffer sb = new StringBuffer();
+ while (matcher.find()) {
+ String value = (item != null) ? extractText(item, matcher.group(1).trim()) : "";
+ matcher.appendReplacement(sb,
+ Matcher.quoteReplacement(MessageUtil.stripControlChars(value)));
+ }
+ matcher.appendTail(sb);
+ return sb.toString();
+ }
+
+ /** JsonNode 에서 dot 경로로 값을 꺼낸다. 값 노드가 아니면 JSON 문자열 그대로 반환. */
+ private String extractText(JsonNode node, String path) {
+
+ JsonNode current = node;
+ for (String part : path.split("\\.", -1)) {
+ if (current == null) {
+ return "";
+ }
+ current = current.get(part);
+ }
+ if (current == null || current.isNull()) {
+ return "";
+ }
+ return current.isValueNode() ? current.asText() : current.toString();
+ }
+
+ /** 요청 전문에서 dot 경로로 배열 노드를 꺼낸다. */
+ private JsonNode readRequestArray(Properties prop, String sourcePath) {
+
+ String requestMessage = prop.getProperty(CP_INBOUND_REQUEST_MESSAGE);
+ if (StringUtils.isBlank(requestMessage)) {
+ return null;
+ }
+
+ try {
+ // 상대 시스템이 제어문자를 이스케이프하지 않고 보내는 경우가 있어 정규화 후 파싱한다.
+ JsonNode node = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(requestMessage));
+ for (String part : sourcePath.split("\\.", -1)) {
+ if (node == null) {
+ return null;
+ }
+ node = node.get(part);
+ }
+ return node;
+ } catch (Exception e) {
+ if (logger.isWarn()) {
+ logger.warn("ApiTemplateAdapterErrorMsgHandler] request parse fail - " + e.getMessage());
+ }
+ return null;
+ }
+ }
+
+ // ================================================================
+ // 설정 조회
+ // ================================================================
+
+ /**
+ * 템플릿 조회. API ID 별 → 공통 순으로 찾고, 그래도 없으면 기본 템플릿으로 폴백한다.
+ *
+ * infix="sys." → {apiId}.sys.template → sys.template → {apiId}.template → template
+ * infix="" → {apiId}.template → template
+ *
+ * 경로별로 응답을 달리 할 필요가 없으면 {@code sys.template}/{@code in.template} 을
+ * 등록하지 않아도 된다. 이때 코드/메시지는 매핑의 default 로 떨어진다.
+ */
+ private String findTemplate(String group, String apiId, String infix) {
+
+ String template = getApiProp(group, apiId, infix + "template");
+ if (StringUtils.isNotBlank(template)) {
+ return template;
+ }
+
+ template = getProp(group, infix + "template");
+ if (StringUtils.isNotBlank(template)) {
+ return template;
+ }
+
+ if (StringUtils.isBlank(infix)) {
+ return null;
+ }
+
+ // sys / in 전용 템플릿이 없으면 업무오류용 기본 템플릿을 그대로 쓴다
+ template = getApiProp(group, apiId, "template");
+ if (StringUtils.isNotBlank(template)) {
+ return template;
+ }
+ return getProp(group, "template");
+ }
+
+ /** "{apiId}.{suffix}" 설정 값. apiId 가 없으면 null. */
+ private String getApiProp(String group, String apiId, String suffix) {
+
+ if (StringUtils.isBlank(apiId)) {
+ return null;
+ }
+ return getProp(group, apiId + "." + suffix);
+ }
+
+ /**
+ * API ID 를 구한다. api.key 로 지정한 callProp 값을 그대로 쓴다.
+ * (기본 API_SERVICE_CODE. FINAL_STD_MESSAGE_KEY 로 바꾸면 요청 경로가 API ID 가 된다)
+ */
+ private String resolveApiId(String group, Properties callProp) {
+
+ String apiKey = StringUtils.defaultIfBlank(getProp(group, KEY_API_KEY), DEFAULT_API_KEY);
+ String apiId = callProp.getProperty(apiKey);
+
+ if (StringUtils.isBlank(apiId) && logger.isWarn()) {
+ logger.warn("ApiTemplateAdapterErrorMsgHandler] api id value not found. key=" + apiKey);
+ }
+ return apiId;
+ }
+
+ /**
+ * 표준전문 오류코드를 찾는다.
+ * 표준전문 경로 → EAIMessage 응답코드 → callProp INBOUND_RESULT_CODE 순.
+ */
+ private String resolveErrorCode(String group, StandardMessage stdMsg, EAIMessage resEaiMsg,
+ Properties callProp) {
+
+ if (stdMsg != null) {
+ String path = StringUtils.defaultIfBlank(getProp(group, KEY_ERR_CODE_PATH), DEFAULT_ERR_CODE_PATH);
+ String code = stdMsg.findItemValue(path);
+ if (StringUtils.isNotBlank(code)) {
+ return code;
+ }
+ }
+
+ if (resEaiMsg != null && StringUtils.isNotBlank(resEaiMsg.getRspErrCd())) {
+ return resEaiMsg.getRspErrCd();
+ }
+
+ if (callProp != null) {
+ return StringUtils.trimToEmpty(callProp.getProperty(CP_INBOUND_RESULT_CODE));
+ }
+ return "";
+ }
+
+ /** {접두어}{오류코드} → 없으면 {접두어}default → 없으면 빈 문자열 */
+ private String mapValue(String group, String prefix, String errorCode) {
+
+ if (StringUtils.isNotBlank(errorCode)) {
+ String mapped = getProp(group, prefix + errorCode);
+ if (mapped != null) {
+ return mapped;
+ }
+ }
+ return StringUtils.defaultString(getProp(group, prefix + KEY_DEFAULT_SUFFIX));
+ }
+
+ /**
+ * 설정 값 조회. 서브클래스가 다른 저장소에서 읽거나
+ * 단위테스트에서 PropManager 없이 검증할 수 있게 분리한다.
+ */
+ protected String getProp(String group, String key) {
+ return PropManager.getInstance().getProperty(group, key);
+ }
+}
diff --git a/src/main/java/com/eactive/eai/adapter/handler/TemplateAdapterErrorMsgHandler.java b/src/main/java/com/eactive/eai/adapter/handler/TemplateAdapterErrorMsgHandler.java
index 967df54..d2ee252 100644
--- a/src/main/java/com/eactive/eai/adapter/handler/TemplateAdapterErrorMsgHandler.java
+++ b/src/main/java/com/eactive/eai/adapter/handler/TemplateAdapterErrorMsgHandler.java
@@ -161,9 +161,10 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
/**
* 템플릿에 StandardMessage, callProp, exception 값을 치환해 최종 문자열을 반환한다.
* foreach 블록과 스칼라 변수를 좌→우 순서로 단일 패스 처리한다.
- * package-private: 단위 테스트에서 직접 호출 가능
+ * protected: 다른 패키지의 확장 핸들러가 템플릿 조회는 직접 하고 렌더만 재사용할 수 있게 공개한다.
+ * (단위 테스트는 같은 패키지에서 직접 호출)
*/
- String render(String template, StandardMessage msg, Properties callProp, Throwable exception) {
+ protected String render(String template, StandardMessage msg, Properties callProp, Throwable exception) {
// 관리 UI 등에서 HTML 인코딩된 엔티티를 복원 (예: # → #)
template = template.replace("#", "#")
.replace("&", "&")
diff --git a/src/test/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandlerTest.java b/src/test/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandlerTest.java
new file mode 100644
index 0000000..b0a3fc6
--- /dev/null
+++ b/src/test/java/com/eactive/eai/adapter/handler/ApiTemplateAdapterErrorMsgHandlerTest.java
@@ -0,0 +1,663 @@
+package com.eactive.eai.adapter.handler;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.util.Properties;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+import com.eactive.eai.common.message.EAIMessage;
+import com.eactive.eai.message.StandardItem;
+import com.eactive.eai.message.StandardMessage;
+import com.eactive.eai.message.StandardType;
+
+/**
+ * ApiTemplateAdapterErrorMsgHandler 단위테스트
+ *
+ * PropManager 는 getProp 를 오버라이드한 테스트용 서브클래스로 대체한다. + * (스프링 컨텍스트 없이 설정만 갈아끼워 검증) + * + *
설정 값은 카카오뱅크 연동 기준 예시를 사용한다. + */ +class ApiTemplateAdapterErrorMsgHandlerTest { + + /** API ID (API_SERVICE_CODE 값) */ + private static final String API_CANCEL = "KKBAL004"; + private static final String API_APPLY = "KKBAL002"; + private static final String API_STATUS = "KKBAL003"; + private static final String API_CREDITLINE = "KKBAL001"; + + private Properties config; + private ApiTemplateAdapterErrorMsgHandler handler; + + /** 설정을 메모리 Properties 로 대체한 핸들러 (PropManager 미사용) */ + private class TestHandler extends ApiTemplateAdapterErrorMsgHandler { + @Override + protected String getPropGroup(String adapterGroupName) { + return "TEST_GROUP_PROPS"; + } + + @Override + protected String getProp(String group, String key) { + return config.getProperty(key); + } + } + + @BeforeEach + void setUp() { + config = new Properties(); + handler = new TestHandler(); + + // 코드 / 메시지 매핑 (일부만) + config.setProperty("rslt_cd.40000", "CP4000"); + config.setProperty("rslt_cd.40400", "CP5002"); + config.setProperty("rslt_cd.50401", "CP5001"); + config.setProperty("rslt_cd.default", "CP5000"); + config.setProperty("rslt_msg.40000", "기타 형식 오류입니다"); + config.setProperty("rslt_msg.40400", "네트워크 오류가 발생하였습니다"); + config.setProperty("rslt_msg.50401", "시스템 내부 처리도중 오류가 발생하였습니다"); + config.setProperty("rslt_msg.default", "기타 시스템 오류입니다."); + + // API ID 별 템플릿 + config.setProperty(API_CANCEL + ".template", + "{\"iqry_dman_no\":\"${callprop.INBOUND_REQUEST_MESSAGE.iqry_dman_no}\"," + + "\"rslt_cd\":\"${rslt_cd}\"," + + "\"rejectd_rsn_ctnt\":\"${rslt_msg}\"}"); + + config.setProperty(API_APPLY + ".template", + "{\"iqry_dman_no\":\"${callprop.INBOUND_REQUEST_MESSAGE.iqry_dman_no}\"," + + "\"rslt_cd\":\"${rslt_cd}\"}"); + + config.setProperty(API_STATUS + ".template", "{\"iqry_dman_nos\":${array}}"); + config.setProperty(API_STATUS + ".array.source", "iqry_dman_nos"); + config.setProperty(API_STATUS + ".array.item", + "{\"iqry_dman_no\":\"${item.iqry_dman_no}\"," + + "\"rslt_cd\":\"${rslt_cd}\"," + + "\"alin_rslt_ctnt\":\"${rslt_msg}\"}"); + + config.setProperty(API_CREDITLINE + ".template", "{\"alnc_gds_infos\":${array}}"); + config.setProperty(API_CREDITLINE + ".array.source", "alnc_gds_infos"); + config.setProperty(API_CREDITLINE + ".array.item", + "{\"iqry_dman_no\":\"${item.iqry_dman_no}\"," + + "\"alnc_prgr_cd\":\"${item.alnc_prgr_cd}\"," + + "\"alnc_gds_unq_cd\":\"${item.alnc_gds_unq_cd}\"," + + "\"rslt_cd\":\"${rslt_cd}\"," + + "\"rejectd_rsn_ctnt\":\"${rslt_msg}\"}"); + } + + // ================================================================ + // 헬퍼 + // ================================================================ + + private static StandardItem field(String name, String value) { + return new StandardItem(name, 3, StandardType.FIELD, 1, 0, 300, 1, "", "", value, name); + } + + private static StandardItem group(String name) { + return new StandardItem(name, 2, StandardType.GROUP, 1, 0, 0, 1, "", "", null, name); + } + + /** MSG.MAIN_MSG.outp_msg_cd 만 있는 최소 표준전문 */ + private static StandardMessage buildMsg(String errCode) { + StandardMessage msg = new StandardMessage(); + StandardItem msgGroup = group("MSG"); + StandardItem mainMsg = group("MAIN_MSG"); + mainMsg.addItem(field("outp_msg_cd", errCode)); + mainMsg.addItem(field("outp_msg_ctnt", "오류")); + msgGroup.addItem(mainMsg); + msg.addItem(msgGroup); + return msg; + } + + /** 표준전문만 실어둔 최소 EAIMessage */ + private static EAIMessage toEaiMessage(StandardMessage msg) { + EAIMessage eaiMessage = new EAIMessage(); + eaiMessage.setStandardMessage(msg); + return eaiMessage; + } + + /** API_SERVICE_CODE + 요청 전문을 실은 거래 Properties */ + private static Properties callProp(String apiServiceCode, String requestMessage) { + Properties prop = new Properties(); + prop.setProperty("API_SERVICE_CODE", apiServiceCode); + if (requestMessage != null) { + prop.setProperty("INBOUND_REQUEST_MESSAGE", requestMessage); + } + return prop; + } + + private Object callBusinessError(Properties prop, String errCode) throws Exception { + return handler.generateNonStandardErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg(errCode))); + } + + // ================================================================ + // 단일 응답 API + // ================================================================ + + @Nested + @DisplayName("단일 응답 API") + class SingleResponse { + + @Test + @DisplayName("요청 에코 + 코드/메시지 매핑") + void 요청에코_매핑() throws Exception { + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A0001\"}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_no\":\"A0001\"," + + "\"rslt_cd\":\"CP4000\"," + + "\"rejectd_rsn_ctnt\":\"기타 형식 오류입니다\"}", result); + } + + @Test + @DisplayName("API 별로 다른 템플릿 사용") + void API별_템플릿() throws Exception { + Properties prop = callProp(API_APPLY, "{\"iqry_dman_no\":\"A0002\"}"); + + Object result = callBusinessError(prop, "50401"); + + assertEquals("{\"iqry_dman_no\":\"A0002\",\"rslt_cd\":\"CP5001\"}", result); + } + + @Test + @DisplayName("매핑 없는 오류코드 → default 로 폴백") + void 매핑없는_코드_default() throws Exception { + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A0003\"}"); + + Object result = callBusinessError(prop, "99999"); + + assertEquals("{\"iqry_dman_no\":\"A0003\"," + + "\"rslt_cd\":\"CP5000\"," + + "\"rejectd_rsn_ctnt\":\"기타 시스템 오류입니다.\"}", result); + } + + @Test + @DisplayName("요청 전문이 없으면 에코 필드는 빈 값") + void 요청전문_없음() throws Exception { + Properties prop = callProp(API_APPLY, null); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_no\":\"\",\"rslt_cd\":\"CP4000\"}", result); + } + } + + // ================================================================ + // 배열 응답 API + // ================================================================ + + @Nested + @DisplayName("배열 응답 API") + class ArrayResponse { + + @Test + @DisplayName("요청 배열 2건을 그대로 반복") + void 배열_2건() throws Exception { + Properties prop = callProp(API_STATUS, + "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"},{\"iqry_dman_no\":\"A002\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"A001\",\"rslt_cd\":\"CP4000\",\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}," + + "{\"iqry_dman_no\":\"A002\",\"rslt_cd\":\"CP4000\",\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}" + + "]}", result); + } + + @Test + @DisplayName("요소 3필드 에코") + void 요소_3필드_에코() throws Exception { + Properties prop = callProp(API_CREDITLINE, + "{\"alnc_gds_infos\":[{\"iqry_dman_no\":\"B001\",\"alnc_prgr_cd\":\"10\"," + + "\"alnc_gds_unq_cd\":\"G0001\"}]}"); + + Object result = callBusinessError(prop, "40400"); + + assertEquals("{\"alnc_gds_infos\":[" + + "{\"iqry_dman_no\":\"B001\",\"alnc_prgr_cd\":\"10\",\"alnc_gds_unq_cd\":\"G0001\"," + + "\"rslt_cd\":\"CP5002\",\"rejectd_rsn_ctnt\":\"네트워크 오류가 발생하였습니다\"}" + + "]}", result); + } + + @Test + @DisplayName("선행 0 이 있는 값도 문자열 그대로 유지") + void 선행0_유지() throws Exception { + Properties prop = callProp(API_STATUS, + "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"000123\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"000123\",\"rslt_cd\":\"CP4000\"," + + "\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}]}", result); + } + + @Test + @DisplayName("요청 배열이 없어도 오류코드를 담아 1건으로 응답") + void 요청배열_없음() throws Exception { + Properties prop = callProp(API_STATUS, "{\"other\":\"x\"}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"\",\"rslt_cd\":\"CP4000\"," + + "\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}]}", result); + } + + @Test + @DisplayName("요청 전문이 깨진 JSON 이어도 오류코드를 담아 1건으로 응답") + void 요청전문_파싱실패() throws Exception { + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"\",\"rslt_cd\":\"CP4000\"," + + "\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}]}", result); + } + + @Test + @DisplayName("요청 전문 자체가 없어도 1건으로 응답") + void 요청전문_없음_배열API() throws Exception { + Properties prop = callProp(API_CREDITLINE, null); + + Object result = callBusinessError(prop, "40400"); + + assertEquals("{\"alnc_gds_infos\":[" + + "{\"iqry_dman_no\":\"\",\"alnc_prgr_cd\":\"\",\"alnc_gds_unq_cd\":\"\"," + + "\"rslt_cd\":\"CP5002\",\"rejectd_rsn_ctnt\":\"네트워크 오류가 발생하였습니다\"}]}", result); + } + + @Test + @DisplayName("요청 배열이 빈 배열이어도 1건으로 응답") + void 요청배열_빈배열() throws Exception { + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"\",\"rslt_cd\":\"CP4000\"," + + "\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}]}", result); + } + + @Test + @DisplayName("array.item 만 있고 array.source 가 없으면 배열로 처리하지 않는다") + void array_source_없음() throws Exception { + config.remove(API_STATUS + ".array.source"); + config.setProperty(API_STATUS + ".template", "{\"rslt_cd\":\"${rslt_cd}\"}"); + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"rslt_cd\":\"CP4000\"}", result); + } + + @Test + @DisplayName("배열이 아닌 API 에서 ${array} 는 빈 문자열") + void array_별칭_배열아닌API() throws Exception { + config.setProperty(API_CANCEL + ".template", "{\"rows\":\"${array}\"}"); + Properties prop = callProp(API_CANCEL, "{}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"rows\":\"\"}", result); + } + } + + // ================================================================ + // 템플릿 변수 + // ================================================================ + + @Nested + @DisplayName("템플릿 변수") + class TemplateVariables { + + @Test + @DisplayName("내부 키 표기(${callprop.TPL_RSLT_CD} 등)도 그대로 동작") + void 내부키_표기() throws Exception { + config.setProperty(API_CANCEL + ".template", + "{\"rslt_cd\":\"${callprop.TPL_RSLT_CD}\",\"rejectd_rsn_ctnt\":\"${callprop.TPL_RSLT_MSG}\"}"); + Properties prop = callProp(API_CANCEL, "{}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"rslt_cd\":\"CP4000\",\"rejectd_rsn_ctnt\":\"기타 형식 오류입니다\"}", result); + } + + @Test + @DisplayName("배열 요소도 ${callprop.TPL_ITEM.필드} 표기로 참조 가능") + void 내부키_ITEM_표기() throws Exception { + config.setProperty(API_STATUS + ".array.item", + "{\"iqry_dman_no\":\"${callprop.TPL_ITEM.iqry_dman_no}\",\"rslt_cd\":\"${rslt_cd}\"}"); + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\",\"rslt_cd\":\"CP4000\"}]}", result); + } + + @Test + @DisplayName("${callprop.TPL_ARRAY} 표기도 동작") + void 내부키_ARRAY_표기() throws Exception { + config.setProperty(API_STATUS + ".template", "{\"iqry_dman_nos\":${callprop.TPL_ARRAY}}"); + config.setProperty(API_STATUS + ".array.item", "{\"no\":\"${item.iqry_dman_no}\"}"); + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[{\"no\":\"A001\"}]}", result); + } + + @Test + @DisplayName("${item.*} 는 배열 요소 밖에서는 빈 값") + void item_별칭_배열밖() throws Exception { + config.setProperty(API_CANCEL + ".template", "{\"x\":\"${item.iqry_dman_no}\"}"); + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A1\"}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"x\":\"\"}", result); + } + + @Test + @DisplayName("${item.경로} 는 중첩 경로도 지원") + void item_별칭_중첩경로() throws Exception { + config.setProperty(API_STATUS + ".array.item", "{\"no\":\"${item.detail.iqry_dman_no}\"}"); + Properties prop = callProp(API_STATUS, + "{\"iqry_dman_nos\":[{\"detail\":{\"iqry_dman_no\":\"A001\"}}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[{\"no\":\"A001\"}]}", result); + } + + @Test + @DisplayName("요소에 없는 필드는 빈 값") + void item_별칭_없는필드() throws Exception { + config.setProperty(API_STATUS + ".array.item", "{\"no\":\"${item.none}\"}"); + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_nos\":[{\"no\":\"\"}]}", result); + } + } + + // ================================================================ + // API ID 결정 + // ================================================================ + + @Nested + @DisplayName("API ID 결정") + class ApiIdResolution { + + @Test + @DisplayName("api.key 기본값은 API_SERVICE_CODE") + void api_key_기본값() throws Exception { + Properties prop = new Properties(); + prop.setProperty("API_SERVICE_CODE", API_CANCEL); + prop.setProperty("INBOUND_REQUEST_MESSAGE", "{\"iqry_dman_no\":\"A1\"}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"iqry_dman_no\":\"A1\"," + + "\"rslt_cd\":\"CP4000\"," + + "\"rejectd_rsn_ctnt\":\"기타 형식 오류입니다\"}", result); + } + + @Test + @DisplayName("api.key 를 바꾸면 다른 callProp 키를 API ID 로 사용") + void api_key_변경() throws Exception { + config.setProperty("api.key", "FINAL_STD_MESSAGE_KEY"); + config.setProperty("POST/api/v1/kkb/loan/cancel.template", "{\"rslt_cd\":\"${rslt_cd}\"}"); + + Properties prop = new Properties(); + prop.setProperty("FINAL_STD_MESSAGE_KEY", "POST/api/v1/kkb/loan/cancel"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"rslt_cd\":\"CP4000\"}", result); + } + + @Test + @DisplayName("등록되지 않은 API ID 는 공통 template 으로 폴백") + void 공통_template_폴백() throws Exception { + config.setProperty("template", "{\"rslt_cd\":\"${rslt_cd}\"}"); + Properties prop = callProp("KKBAL999", "{}"); + + Object result = callBusinessError(prop, "40000"); + + assertEquals("{\"rslt_cd\":\"CP4000\"}", result); + } + + @Test + @DisplayName("API ID 값 자체가 없어도 공통 template 으로 응답") + void 식별값_없음() throws Exception { + config.setProperty("template", "{\"rslt_cd\":\"${rslt_cd}\"}"); + + Object result = callBusinessError(new Properties(), "40000"); + + assertEquals("{\"rslt_cd\":\"CP4000\"}", result); + } + } + + // ================================================================ + // sys / in 경로 + // ================================================================ + + @Nested + @DisplayName("sys / in 경로") + class SysAndInbound { + + @Test + @DisplayName("sys – 공통 sys.template 사용") + void sys_공통템플릿() throws Exception { + config.setProperty("sys.template", "{\"rslt_cd\":\"${rslt_cd}\",\"rejectd_rsn_ctnt\":\"${rslt_msg}\"}"); + Properties prop = callProp(API_STATUS, "{}"); + + Object result = handler.generateNonStandardInternalErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg("50401"))); + + assertEquals("{\"rslt_cd\":\"CP5001\"," + + "\"rejectd_rsn_ctnt\":\"시스템 내부 처리도중 오류가 발생하였습니다\"}", result); + } + + @Test + @DisplayName("sys – API ID 별 템플릿이 공통보다 우선") + void sys_API별템플릿_우선() throws Exception { + config.setProperty("sys.template", "{\"common\":\"y\"}"); + config.setProperty(API_STATUS + ".sys.template", + "{\"api\":\"status\",\"rslt_cd\":\"${rslt_cd}\"}"); + Properties prop = callProp(API_STATUS, "{}"); + + Object result = handler.generateNonStandardInternalErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg("50401"))); + + assertEquals("{\"api\":\"status\",\"rslt_cd\":\"CP5001\"}", result); + } + + @Test + @DisplayName("in – StandardMessage 없이 INBOUND_RESULT_CODE 로 매핑") + void in_INBOUND_RESULT_CODE() throws Exception { + config.setProperty("in.template", "{\"rslt_cd\":\"${rslt_cd}\",\"rejectd_rsn_ctnt\":\"${rslt_msg}\"}"); + Properties prop = callProp(API_STATUS, "{}"); + prop.setProperty("INBOUND_RESULT_CODE", "40400"); + + Object result = handler.generateNonStandardInboundErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, null, new RuntimeException("filter fail")); + + assertEquals("{\"rslt_cd\":\"CP5002\"," + + "\"rejectd_rsn_ctnt\":\"네트워크 오류가 발생하였습니다\"}", result); + } + + @Test + @DisplayName("in – 매핑 없는 GW 코드는 default") + void in_default폴백() throws Exception { + config.setProperty("in.template", "{\"rslt_cd\":\"${rslt_cd}\",\"rejectd_rsn_ctnt\":\"${rslt_msg}\"}"); + Properties prop = callProp(API_STATUS, "{}"); + prop.setProperty("INBOUND_RESULT_CODE", "RECEAIIRP201"); + + Object result = handler.generateNonStandardInboundErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, null, new RuntimeException("filter fail")); + + assertEquals("{\"rslt_cd\":\"CP5000\"," + + "\"rejectd_rsn_ctnt\":\"기타 시스템 오류입니다.\"}", result); + } + + @Test + @DisplayName("sys – 전용 템플릿이 없으면 {apiId}.template 을 그대로 사용") + void sys_기본템플릿_폴백() throws Exception { + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A0001\"}"); + + Object result = handler.generateNonStandardInternalErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg("50401"))); + + assertEquals("{\"iqry_dman_no\":\"A0001\"," + + "\"rslt_cd\":\"CP5001\"," + + "\"rejectd_rsn_ctnt\":\"시스템 내부 처리도중 오류가 발생하였습니다\"}", result); + } + + @Test + @DisplayName("in – 전용 템플릿이 없으면 {apiId}.template 을 그대로 사용") + void in_기본템플릿_폴백() throws Exception { + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A0001\"}"); + prop.setProperty("INBOUND_RESULT_CODE", "40400"); + + Object result = handler.generateNonStandardInboundErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, null, new RuntimeException("filter fail")); + + assertEquals("{\"iqry_dman_no\":\"A0001\"," + + "\"rslt_cd\":\"CP5002\"," + + "\"rejectd_rsn_ctnt\":\"네트워크 오류가 발생하였습니다\"}", result); + } + + @Test + @DisplayName("sys – 배열 API 는 기본 템플릿 폴백 시에도 배열로 응답") + void sys_기본템플릿_폴백_배열() throws Exception { + Properties prop = callProp(API_STATUS, + "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + Object result = handler.generateNonStandardInternalErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg("50401"))); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"A001\",\"rslt_cd\":\"CP5001\"," + + "\"alin_rslt_ctnt\":\"시스템 내부 처리도중 오류가 발생하였습니다\"}]}", result); + } + + @Test + @DisplayName("sys – 공통 sys.template 이 {apiId}.template 보다 우선") + void sys_공통템플릿_우선() throws Exception { + config.setProperty("sys.template", "{\"common\":\"y\"}"); + Properties prop = callProp(API_CANCEL, "{\"iqry_dman_no\":\"A0001\"}"); + + Object result = handler.generateNonStandardInternalErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, toEaiMessage(buildMsg("50401"))); + + assertEquals("{\"common\":\"y\"}", result); + } + + @Test + @DisplayName("in – 배열 API 도 동일하게 배열 응답") + void in_배열API() throws Exception { + config.setProperty(API_STATUS + ".in.template", "{\"iqry_dman_nos\":${array}}"); + Properties prop = callProp(API_STATUS, "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"C001\"}]}"); + prop.setProperty("INBOUND_RESULT_CODE", "40000"); + + Object result = handler.generateNonStandardInboundErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", prop, null, null, new RuntimeException("filter fail")); + + assertEquals("{\"iqry_dman_nos\":[" + + "{\"iqry_dman_no\":\"C001\",\"rslt_cd\":\"CP4000\"," + + "\"alin_rslt_ctnt\":\"기타 형식 오류입니다\"}]}", result); + } + } + + // ================================================================ + // 예외 상황 / 뒷정리 + // ================================================================ + + @Nested + @DisplayName("예외 상황 / 뒷정리") + class EdgeCases { + + @Test + @DisplayName("템플릿이 없으면 null 반환 (상위에서 기본 오류 응답으로 폴백)") + void 템플릿_없음() throws Exception { + config.remove(API_CANCEL + ".template"); + Properties prop = callProp(API_CANCEL, "{}"); + + assertNull(callBusinessError(prop, "40000")); + } + + @Test + @DisplayName("callProp 이 null 이어도 예외 없이 처리") + void callProp_null() throws Exception { + config.setProperty("template", "{\"rslt_cd\":\"${rslt_cd}\"}"); + + Object result = handler.generateNonStandardErrorResponseMessage( + "TEST_GROUP", "TEST_ADAPTER", null, null, toEaiMessage(buildMsg("40000"))); + + assertEquals("{\"rslt_cd\":\"CP4000\"}", result); + } + + @Test + @DisplayName("렌더 후 임시 키가 거래 Properties 에 남지 않는다") + void 임시키_정리() throws Exception { + Properties prop = callProp(API_STATUS, + "{\"iqry_dman_nos\":[{\"iqry_dman_no\":\"A001\"}]}"); + + callBusinessError(prop, "40000"); + + assertFalse(prop.containsKey("TPL_RSLT_CD")); + assertFalse(prop.containsKey("TPL_RSLT_MSG")); + assertFalse(prop.containsKey("TPL_ARRAY")); + assertFalse(prop.containsKey("TPL_ITEM")); + } + + } + + // ================================================================ + // 프로퍼티 그룹 결정 + // ================================================================ + + @Nested + @DisplayName("프로퍼티 그룹 결정") + class PropGroupResolution { + + /** 어댑터 그룹 전용 프로퍼티 그룹이 등록되어 있다고 보는 핸들러 */ + private ApiTemplateAdapterErrorMsgHandler handlerWithGroup(final boolean exists) { + return new ApiTemplateAdapterErrorMsgHandler() { + @Override + protected boolean hasPropGroup(String group) { + return exists; + } + }; + } + + @Test + @DisplayName("어댑터 그룹 전용 프로퍼티 그룹이 있으면 그것을 쓴다") + void 어댑터그룹_전용그룹() { + assertEquals("ERR{KKB_LOAN}", handlerWithGroup(true).getPropGroup("KKB_LOAN")); + } + + @Test + @DisplayName("전용 그룹이 없으면 기본 그룹으로 폴백") + void 기본그룹_폴백() { + assertEquals("ERR{API}", handlerWithGroup(false).getPropGroup("KKB_LOAN")); + } + + @Test + @DisplayName("어댑터 그룹명이 없으면 기본 그룹") + void 어댑터그룹명_없음() { + assertEquals("ERR{API}", handlerWithGroup(true).getPropGroup(null)); + } + } +}