diff options
| author | joonhoekim <26rote@gmail.com> | 2025-11-18 18:34:52 +0900 |
|---|---|---|
| committer | joonhoekim <26rote@gmail.com> | 2025-11-18 18:34:52 +0900 |
| commit | 76a6606def50caa4df28014b869a06e5da30ab18 (patch) | |
| tree | d1dd318b959c91dad3be22c7a60383da434a4ad7 /lib/soap/sender.ts | |
| parent | c7d76d044531aab65dde9ba1007f3b2d86da6326 (diff) | |
(김준회) 견적: PO 생성 요청부 개선, 에러처리
Diffstat (limited to 'lib/soap/sender.ts')
| -rw-r--r-- | lib/soap/sender.ts | 103 |
1 files changed, 55 insertions, 48 deletions
diff --git a/lib/soap/sender.ts b/lib/soap/sender.ts index d12665cb..c0be780d 100644 --- a/lib/soap/sender.ts +++ b/lib/soap/sender.ts @@ -3,43 +3,13 @@ import { withSoapLogging } from "@/lib/soap/utils"; import { XMLBuilder } from 'fast-xml-parser'; import { debugLog, debugError, debugWarn, debugSuccess } from '@/lib/debug-utils'; - -// 기본 인증 정보 타입 -export interface SoapAuthConfig { - username?: string; - password?: string; -} - -// SOAP 전송 설정 타입 -export interface SoapSendConfig { - endpoint: string; - envelope: Record<string, unknown>; - soapAction?: string; - timeout?: number; - retryCount?: number; - retryDelay?: number; - namespace?: string; // 네임스페이스를 동적으로 설정할 수 있도록 추가 - prefix: string; // 네임스페이스 접두사 (필수) -} - -// 로깅 정보 타입 -export interface SoapLogInfo { - direction: 'INBOUND' | 'OUTBOUND'; - system: string; - interface: string; -} - -// 전송 결과 타입 -export interface SoapSendResult { - success: boolean; - message: string; - responseText?: string; - statusCode?: number; - headers?: Record<string, string>; - endpoint?: string; - requestXml?: string; - requestHeaders?: Record<string, string>; -} +import type { + SoapAuthConfig, + SoapSendConfig, + SoapLogInfo, + SoapSendResult +} from './types'; +import { SoapResponseError } from './types'; // 기본 환경변수에서 인증 정보 가져오기 function getDefaultAuth(): SoapAuthConfig { @@ -154,6 +124,7 @@ export async function sendSoapXml( } } + let responseText = ''; const result = await withSoapLogging( logInfo.direction, logInfo.system, @@ -161,17 +132,17 @@ export async function sendSoapXml( xmlData, async () => { // 타임아웃 설정 + let response: Response; if (config.timeout) { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), config.timeout); try { - const response = await fetch(config.endpoint, { + response = await fetch(config.endpoint, { ...fetchOptions, signal: controller.signal }); clearTimeout(timeoutId); - return response; } catch (error) { clearTimeout(timeoutId); if (error instanceof Error && error.name === 'AbortError') { @@ -180,14 +151,20 @@ export async function sendSoapXml( throw error; } } else { - return await fetch(config.endpoint, fetchOptions); + response = await fetch(config.endpoint, fetchOptions); } - } + + // 응답 텍스트 읽기 (로깅을 위해 여기서 읽음) + responseText = await response.text(); + + return response; + }, + // 응답 데이터 추출 함수: responseText를 반환 + () => responseText ); // 응답 처리 const response = result as Response; - const responseText = await response.text(); // 응답 헤더 수집 (디버깅용) const responseHeadersDebug: Record<string, string> = {}; @@ -203,22 +180,52 @@ export async function sendSoapXml( }); debugLog('🔍 응답 바디 (전체):', responseText); - // HTTP 상태 코드가 비정상이거나 SOAP Fault 포함 시 실패로 처리하되 본문을 그대로 반환 - if (!response.ok || responseText.includes('soap:Fault') || responseText.includes('SOAP:Fault')) { + // SAP 응답 에러 체크: <MSGTY>E</MSGTY> 또는 <EV_TYPE>E</EV_TYPE> 패턴 감지 + const hasSapError = responseText.includes('<MSGTY>E</MSGTY>') || + responseText.includes('<EV_TYPE>E</EV_TYPE>'); + + // HTTP 상태 코드가 비정상이거나 SOAP Fault 또는 SAP 에러 포함 시 실패로 처리 + if (!response.ok || + responseText.includes('soap:Fault') || + responseText.includes('SOAP:Fault') || + hasSapError) { const responseHeaders: Record<string, string> = {}; response.headers.forEach((value, key) => { responseHeaders[key] = value; }); - return { - success: false, - message: !response.ok ? `HTTP ${response.status}: ${response.statusText}` : 'SOAP Fault', + + // 에러 메시지 결정 및 상세 메시지 추출 + let errorMessage = ''; + if (!response.ok) { + errorMessage = `HTTP ${response.status}: ${response.statusText}`; + } else if (hasSapError) { + // SAP 응답에서 에러 메시지 추출 시도 + const msgtxtMatch = responseText.match(/<MSGTXT>(.*?)<\/MSGTXT>/); + const evMessageMatch = responseText.match(/<EV_MESSAGE>(.*?)<\/EV_MESSAGE>/); + const detailMessage = msgtxtMatch?.[1] || evMessageMatch?.[1] || ''; + + errorMessage = 'SAP 응답 에러: MSGTY=E 또는 EV_TYPE=E 감지'; + if (detailMessage) { + errorMessage += ` - ${detailMessage}`; + } + } else { + // SOAP Fault에서 메시지 추출 시도 + const faultStringMatch = responseText.match(/<faultstring>(.*?)<\/faultstring>/); + const faultMessage = faultStringMatch?.[1] || 'SOAP Fault'; + errorMessage = faultMessage; + } + + debugError('❌ SOAP 응답 에러 감지:', errorMessage); + + // 커스텀 에러 객체 생성 (responseText 포함) + throw new SoapResponseError(errorMessage, { responseText, statusCode: response.status, headers: responseHeaders, endpoint: config.endpoint, requestXml: xmlData, requestHeaders - }; + }); } // 응답 헤더 수집 |
