fix: API 응답 파싱 오류 수정 및 에러 처리 개선
주요 변경사항: - 창고 관리 API 응답 구조와 DTO 불일치 수정 - WarehouseLocationDto에 code, manager_phone 필드 추가 - RemoteDataSource에서 API 응답을 DTO 구조에 맞게 변환 - 회사 관리 API 응답 파싱 오류 수정 - CompanyResponse의 필수 필드를 nullable로 변경 - PaginatedResponse 구조 매핑 로직 개선 - 에러 처리 및 로깅 개선 - Service Layer에 상세 에러 로깅 추가 - Controller에서 에러 타입별 처리 - 새로운 유틸리티 추가 - ResponseInterceptor: API 응답 정규화 - DebugLogger: 디버깅 도구 - HealthCheckService: 서버 상태 확인 - 문서화 - API 통합 테스트 가이드 - 에러 분석 보고서 - 리팩토링 계획서
This commit is contained in:
@@ -6,6 +6,9 @@ import '../../../../services/auth_service.dart';
|
||||
/// 인증 인터셉터
|
||||
class AuthInterceptor extends Interceptor {
|
||||
AuthService? _authService;
|
||||
final Dio dio;
|
||||
|
||||
AuthInterceptor(this.dio);
|
||||
|
||||
AuthService? get authService {
|
||||
try {
|
||||
@@ -22,22 +25,34 @@ class AuthInterceptor extends Interceptor {
|
||||
RequestOptions options,
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
print('[AuthInterceptor] onRequest: ${options.method} ${options.path}');
|
||||
|
||||
// 로그인, 토큰 갱신 요청은 토큰 없이 진행
|
||||
if (_isAuthEndpoint(options.path)) {
|
||||
print('[AuthInterceptor] Auth endpoint detected, skipping token attachment');
|
||||
handler.next(options);
|
||||
return;
|
||||
}
|
||||
|
||||
// 저장된 액세스 토큰 가져오기
|
||||
final service = authService;
|
||||
print('[AuthInterceptor] AuthService available: ${service != null}');
|
||||
|
||||
if (service != null) {
|
||||
final accessToken = await service.getAccessToken();
|
||||
print('[AuthInterceptor] Access token retrieved: ${accessToken != null ? 'Yes (${accessToken.substring(0, 10)}...)' : 'No'}');
|
||||
|
||||
if (accessToken != null) {
|
||||
options.headers['Authorization'] = 'Bearer $accessToken';
|
||||
print('[AuthInterceptor] Authorization header set: Bearer ${accessToken.substring(0, 10)}...');
|
||||
} else {
|
||||
print('[AuthInterceptor] WARNING: No access token available for protected endpoint');
|
||||
}
|
||||
} else {
|
||||
print('[AuthInterceptor] ERROR: AuthService not available from GetIt');
|
||||
}
|
||||
|
||||
print('[AuthInterceptor] Final headers: ${options.headers}');
|
||||
handler.next(options);
|
||||
}
|
||||
|
||||
@@ -46,16 +61,32 @@ class AuthInterceptor extends Interceptor {
|
||||
DioException err,
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
print('[AuthInterceptor] onError: ${err.response?.statusCode} ${err.message}');
|
||||
|
||||
// 401 Unauthorized 에러 처리
|
||||
if (err.response?.statusCode == 401) {
|
||||
// 인증 관련 엔드포인트는 재시도하지 않음
|
||||
if (_isAuthEndpoint(err.requestOptions.path)) {
|
||||
print('[AuthInterceptor] Auth endpoint 401 error, skipping retry');
|
||||
handler.next(err);
|
||||
return;
|
||||
}
|
||||
|
||||
final service = authService;
|
||||
if (service != null) {
|
||||
print('[AuthInterceptor] Attempting token refresh...');
|
||||
// 토큰 갱신 시도
|
||||
final refreshResult = await service.refreshToken();
|
||||
|
||||
final refreshSuccess = refreshResult.fold(
|
||||
(failure) => false,
|
||||
(tokenResponse) => true,
|
||||
(failure) {
|
||||
print('[AuthInterceptor] Token refresh failed: ${failure.message}');
|
||||
return false;
|
||||
},
|
||||
(tokenResponse) {
|
||||
print('[AuthInterceptor] Token refresh successful');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
if (refreshSuccess) {
|
||||
@@ -64,13 +95,16 @@ class AuthInterceptor extends Interceptor {
|
||||
final newAccessToken = await service.getAccessToken();
|
||||
|
||||
if (newAccessToken != null) {
|
||||
print('[AuthInterceptor] Retrying request with new token');
|
||||
err.requestOptions.headers['Authorization'] = 'Bearer $newAccessToken';
|
||||
|
||||
final response = await Dio().fetch(err.requestOptions);
|
||||
// dio 인스턴스를 통해 재시도
|
||||
final response = await dio.fetch(err.requestOptions);
|
||||
handler.resolve(response);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
print('[AuthInterceptor] Request retry failed: $e');
|
||||
// 재시도 실패
|
||||
handler.next(err);
|
||||
return;
|
||||
@@ -78,6 +112,7 @@ class AuthInterceptor extends Interceptor {
|
||||
}
|
||||
|
||||
// 토큰 갱신 실패 시 로그인 화면으로 이동
|
||||
print('[AuthInterceptor] Clearing session due to auth failure');
|
||||
await service.clearSession();
|
||||
// TODO: Navigate to login screen
|
||||
}
|
||||
|
||||
@@ -63,15 +63,42 @@ class ErrorInterceptor extends Interceptor {
|
||||
break;
|
||||
|
||||
case DioExceptionType.unknown:
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: ServerException(
|
||||
message: AppConstants.unknownError,
|
||||
// CORS 에러 감지 시도
|
||||
final errorMessage = err.message?.toLowerCase() ?? '';
|
||||
final errorString = err.error?.toString().toLowerCase() ?? '';
|
||||
|
||||
if (errorMessage.contains('cors') || errorString.contains('cors') ||
|
||||
errorMessage.contains('xmlhttprequest') || errorString.contains('xmlhttprequest')) {
|
||||
print('[ErrorInterceptor] CORS 에러 감지됨');
|
||||
print('[ErrorInterceptor] 요청 URL: ${err.requestOptions.uri}');
|
||||
print('[ErrorInterceptor] 에러 메시지: ${err.message}');
|
||||
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: NetworkException(
|
||||
message: 'CORS 정책으로 인해 API 접근이 차단되었습니다.\n'
|
||||
'개발 환경에서는 run_web_with_proxy.sh 스크립트를 사용하세요.',
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
);
|
||||
);
|
||||
} else {
|
||||
print('[ErrorInterceptor] 알 수 없는 에러');
|
||||
print('[ErrorInterceptor] 에러 타입: ${err.error?.runtimeType}');
|
||||
print('[ErrorInterceptor] 에러 메시지: ${err.message}');
|
||||
print('[ErrorInterceptor] 에러 내용: ${err.error}');
|
||||
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: ServerException(
|
||||
message: AppConstants.unknownError,
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -90,8 +117,26 @@ class ErrorInterceptor extends Interceptor {
|
||||
// API 응답에서 에러 메시지 추출
|
||||
if (data != null) {
|
||||
if (data is Map) {
|
||||
message = data['message'] ?? data['error'] ?? message;
|
||||
errors = data['errors'] as Map<String, dynamic>?;
|
||||
// error 필드가 객체인 경우 처리
|
||||
if (data['error'] is Map) {
|
||||
final errorObj = data['error'] as Map<String, dynamic>;
|
||||
message = errorObj['message'] ?? message;
|
||||
// code 필드도 저장 (필요시 사용)
|
||||
final errorCode = errorObj['code'];
|
||||
if (errorCode != null) {
|
||||
errors = {'code': errorCode};
|
||||
}
|
||||
} else {
|
||||
// 일반적인 경우: message 또는 error가 문자열
|
||||
message = data['message'] ??
|
||||
(data['error'] is String ? data['error'] : null) ??
|
||||
message;
|
||||
}
|
||||
|
||||
// errors 필드가 있는 경우
|
||||
if (data['errors'] is Map) {
|
||||
errors = data['errors'] as Map<String, dynamic>?;
|
||||
}
|
||||
} else if (data is String) {
|
||||
message = data;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import 'package:flutter/foundation.dart';
|
||||
class LoggingInterceptor extends Interceptor {
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
// 요청 시간 기록
|
||||
options.extra['requestTime'] = DateTime.now();
|
||||
|
||||
debugPrint('╔════════════════════════════════════════════════════════════');
|
||||
debugPrint('║ REQUEST');
|
||||
debugPrint('║ REQUEST [${DateTime.now().toIso8601String()}]');
|
||||
debugPrint('╟────────────────────────────────────────────────────────────');
|
||||
debugPrint('║ ${options.method} ${options.uri}');
|
||||
debugPrint('╟────────────────────────────────────────────────────────────');
|
||||
@@ -42,6 +45,10 @@ class LoggingInterceptor extends Interceptor {
|
||||
}
|
||||
}
|
||||
|
||||
debugPrint('║ Timeout Settings:');
|
||||
debugPrint('║ Connect: ${options.connectTimeout}');
|
||||
debugPrint('║ Receive: ${options.receiveTimeout}');
|
||||
debugPrint('║ Send: ${options.sendTimeout}');
|
||||
debugPrint('╚════════════════════════════════════════════════════════════');
|
||||
|
||||
handler.next(options);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// API 응답을 정규화하는 인터셉터
|
||||
///
|
||||
/// 서버 응답 형식에 관계없이 일관된 형태로 데이터를 처리할 수 있도록 함
|
||||
class ResponseInterceptor extends Interceptor {
|
||||
@override
|
||||
void onResponse(Response response, ResponseInterceptorHandler handler) {
|
||||
print('[ResponseInterceptor] 응답 수신: ${response.requestOptions.path}');
|
||||
print('[ResponseInterceptor] 상태 코드: ${response.statusCode}');
|
||||
print('[ResponseInterceptor] 응답 데이터 타입: ${response.data.runtimeType}');
|
||||
|
||||
// 장비 관련 API 응답 상세 로깅
|
||||
if (response.requestOptions.path.contains('equipment')) {
|
||||
print('[ResponseInterceptor] 장비 API 응답 전체: ${response.data}');
|
||||
if (response.data is List && (response.data as List).isNotEmpty) {
|
||||
final firstItem = (response.data as List).first;
|
||||
print('[ResponseInterceptor] 첫 번째 장비 상태: ${firstItem['status']}');
|
||||
}
|
||||
}
|
||||
|
||||
// 200 OK 응답만 처리
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
// 응답 데이터가 Map인 경우만 처리
|
||||
if (response.data is Map<String, dynamic>) {
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
|
||||
// 이미 정규화된 형식인지 확인
|
||||
if (data.containsKey('success') && data.containsKey('data')) {
|
||||
print('[ResponseInterceptor] 이미 정규화된 응답 형식');
|
||||
handler.next(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// API 응답이 직접 데이터를 반환하는 경우
|
||||
// (예: {accessToken: "...", refreshToken: "...", user: {...}})
|
||||
if (_isDirectDataResponse(data)) {
|
||||
print('[ResponseInterceptor] 직접 데이터 응답을 정규화된 형식으로 변환');
|
||||
|
||||
// 정규화된 응답으로 변환
|
||||
response.data = {
|
||||
'success': true,
|
||||
'data': data,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handler.next(response);
|
||||
}
|
||||
|
||||
/// 직접 데이터 응답인지 확인
|
||||
bool _isDirectDataResponse(Map<String, dynamic> data) {
|
||||
// 로그인 응답 패턴
|
||||
if (data.containsKey('accessToken') ||
|
||||
data.containsKey('access_token') ||
|
||||
data.containsKey('token')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 사용자 정보 응답 패턴
|
||||
if (data.containsKey('user') ||
|
||||
data.containsKey('id') && data.containsKey('email')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 리스트 응답 패턴
|
||||
if (data.containsKey('items') ||
|
||||
data.containsKey('results') ||
|
||||
data.containsKey('data') && data['data'] is List) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 그 외 일반적인 데이터 응답
|
||||
// success, error, message 등의 메타 키가 없으면 데이터 응답으로 간주
|
||||
final metaKeys = ['success', 'error', 'status', 'code'];
|
||||
final hasMetaKey = metaKeys.any((key) => data.containsKey(key));
|
||||
|
||||
return !hasMetaKey;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user