From 5308c11ca6bb9f1481c7fb36c327df100dfa9f68 Mon Sep 17 00:00:00 2001 From: misha Date: Fri, 20 Nov 2026 14:24:20 +0300 Subject: [PATCH] fixed sentry crashes handling --- lib/core/app_initializer.dart | 24 +- .../comments/services/comments_service.dart | 6 +- lib/core/di/external_registrations.dart | 8 +- lib/core/di/repository_registrations.dart | 4 +- lib/core/di/service_registrations.dart | 147 ++++++--- .../error_reporting/api_response_dio.dart | 71 ++++ .../api_response_error_reporter.dart | 111 +++++++ .../error_reporting/error_report_policy.dart | 16 +- lib/core/routing/other_routes.dart | 21 +- lib/core/views/service/views_service.dart | 6 +- lib/core/websockets/ws_service.dart | 6 +- lib/features/auth/services/auth_service.dart | 6 +- .../auth/services/reset_password_service.dart | 6 +- .../barcode/services/barcode_service.dart | 52 +-- .../services/blog_post_service.dart | 6 +- .../calendar/services/calendar_service.dart | 6 +- .../service/cancel_plan_service.dart | 6 +- lib/features/chat/services/chat_service.dart | 6 +- .../services/complaining_service.dart | 6 +- .../services/consultant_service.dart | 6 +- .../services/consultant_rating_service.dart | 6 +- .../services/create_diet_service.dart | 6 +- .../services/create_plan_service.dart | 6 +- .../services/recipe_service.dart | 6 +- .../diary/services/diary_service.dart | 6 +- lib/features/diets/services/diet_service.dart | 6 +- lib/features/feed/services/feed_service.dart | 6 +- .../glossary/services/glossary_service.dart | 6 +- .../insights/services/insights_service.dart | 6 +- .../menu/services/blocked_users_service.dart | 6 +- .../notification_settings_service.dart | 6 +- .../my_diets/services/my_diets_service.dart | 6 +- .../my_finance/services/cards_service.dart | 6 +- .../my_plans/services/my_plans_service.dart | 6 +- .../service/notifications_service.dart | 26 +- .../repositories/payment_repository.dart | 28 +- .../personal_diet_suggestion_service.dart | 7 +- lib/features/plans/services/plan_service.dart | 6 +- .../plans/services/plans_service.dart | 6 +- .../profile/services/profile_service.dart | 6 +- .../recipe/services/about_recipe_service.dart | 6 +- .../recipe/services/my_recipes_service.dart | 6 +- .../services/registration_service.dart | 6 +- .../services/registration_service_v2.dart | 6 +- .../settings/services/settings_service.dart | 6 +- .../services/video_call_service.dart | 6 +- lib/main.dart | 15 +- .../api_response_reporting_test.dart | 311 ++++++++++++++++++ 48 files changed, 909 insertions(+), 136 deletions(-) create mode 100644 lib/core/error_reporting/api_response_dio.dart create mode 100644 lib/core/error_reporting/api_response_error_reporter.dart create mode 100644 test/core/error_reporting/api_response_reporting_test.dart diff --git a/lib/core/app_initializer.dart b/lib/core/app_initializer.dart index 601a7984..86f60dbe 100644 --- a/lib/core/app_initializer.dart +++ b/lib/core/app_initializer.dart @@ -18,21 +18,22 @@ class AppInitializer { static Future initialize({required AppBuildType buildType}) async { await _initializeEnvironment(); await _initializeDependencyInjection(buildType: buildType); - await _initializeSentry(); + _preserveSplash(); await _initializeFirebase(); await _initializeDebugMode(); await _initializeAnalytics(); } - /// Инициализация Sentry - static Future _initializeSentry() async { + static void _preserveSplash() { final widgetsBinding = SentryWidgetsFlutterBinding.ensureInitialized(); FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding); } /// Загрузка переменных окружения static Future _initializeEnvironment() async { - await dotenv.load(fileName: ".env"); + if (!dotenv.isInitialized) { + await dotenv.load(fileName: '.env'); + } } /// Инициализация Firebase @@ -64,20 +65,25 @@ class AppInitializer { /// Инициализация аналитики static Future _initializeAnalytics() async { - AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey)); + AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey, flutterCrashReporting: false)); AppMetrica.reportEvent('Application started'); } /// Запуск приложения с Sentry - static Future runAppWithSentry(VoidCallback appRunner) async { + static Future runAppWithSentry( + FutureOr Function() appRunner, + ) async { + SentryWidgetsFlutterBinding.ensureInitialized(); + await _initializeEnvironment(); + const sendInDebug = bool.fromEnvironment('SENTRY_IN_DEBUG'); await SentryFlutter.init((options) { options.dsn = EnvConfig.sentryDsn; options.tracesSampleRate = 1.0; options.debug = false; + if (kDebugMode && sendInDebug) options.environment = 'debug'; options.beforeSend = (event, hint) { - if (kDebugMode) return null; - if (!ErrorReportPolicy.allowSentryEvent(event, hint)) return null; - return event; + if (kDebugMode && !sendInDebug) return null; + return ErrorReportPolicy.prepareSentryEvent(event, hint); }; }, appRunner: appRunner); } diff --git a/lib/core/comments/services/comments_service.dart b/lib/core/comments/services/comments_service.dart index 606f61bd..6c5a1333 100644 --- a/lib/core/comments/services/comments_service.dart +++ b/lib/core/comments/services/comments_service.dart @@ -6,7 +6,11 @@ part 'comments_service.g.dart'; @RestApi() abstract class CommentsService { - factory CommentsService(Dio dio, {String baseUrl}) = _CommentsService; + factory CommentsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CommentsService; @DELETE('/api/comments/{id}') Future deleteComment(@Path('id') int id); diff --git a/lib/core/di/external_registrations.dart b/lib/core/di/external_registrations.dart index cb285f40..2912633c 100644 --- a/lib/core/di/external_registrations.dart +++ b/lib/core/di/external_registrations.dart @@ -1,6 +1,8 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/constants/app_constants.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; import 'package:eatvio_app/core/error_reporting/sentry_error_reporter.dart'; import 'package:eatvio_app/core/interceptors/phone_verify_error_interceptor.dart'; @@ -18,14 +20,15 @@ class ExternalRegistrations { /// Регистрация всех внешних зависимостей static void registerAll() { sl.registerLazySingleton(SentryErrorReporter.new); + sl.registerLazySingleton(() => ApiResponseErrorReporter(sl())); _registerDio(); _registerPrefs(); } /// Регистрация Dio HTTP клиента static void _registerDio() { - sl.registerLazySingleton( - () => Dio( + sl.registerLazySingleton( + () => ApiResponseDio( BaseOptions( baseUrl: sl().baseUrl, headers: {'accept': 'application/json', 'content-type': 'application/json'}, @@ -33,6 +36,7 @@ class ExternalRegistrations { receiveTimeout: AppConstants.pendingDelay, sendTimeout: AppConstants.pendingDelay, ), + sl(), )..interceptors.addAll([TokenInterceptor(), PhoneVerifyErrorInterceptor()]) ..addSentry( failedRequestStatusCodes: const [SentryStatusCode.defaultRange()], diff --git a/lib/core/di/repository_registrations.dart b/lib/core/di/repository_registrations.dart index 545d009f..6b85d0a6 100644 --- a/lib/core/di/repository_registrations.dart +++ b/lib/core/di/repository_registrations.dart @@ -86,7 +86,9 @@ class RepositoryRegistrations { sl.registerLazySingleton(() => CommentsRepository(service: sl())); sl.registerLazySingleton(() => NotificationSettingsRepository(sl())); sl.registerLazySingleton(() => SbpRepository(sbpService: sl())); - sl.registerLazySingleton(() => PaymentRepository(chatService: sl())); + sl.registerLazySingleton( + () => PaymentRepository(chatService: sl(), responseErrors: sl()), + ); sl.registerLazySingleton(() => PersonalDietSuggestionRepository(personalDietSuggestionService: sl())); sl.registerLazySingleton(() => RegistrationRepositoryV2(registrationService: sl())); diff --git a/lib/core/di/service_registrations.dart b/lib/core/di/service_registrations.dart index abddd8eb..a5022c3f 100644 --- a/lib/core/di/service_registrations.dart +++ b/lib/core/di/service_registrations.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/comments/services/comments_service.dart'; import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/views/service/views_service.dart'; @@ -56,37 +57,83 @@ class ServiceRegistrations { /// Регистрация Service как синглтонов static void _registerSingletonServices() { // Core services - sl.registerLazySingleton(() => ChatService(sl())); - sl.registerLazySingleton(() => VideoCallService(sl())); + sl.registerLazySingleton( + () => ChatService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => VideoCallService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton( () => const PublicDownloadsSaver(), ); sl.registerLazySingleton( () => VideoCallRecordingFileService(dio: sl(), downloadsSaver: sl()), ); - sl.registerLazySingleton(() => FeedService(sl())); - sl.registerLazySingleton(() => ProfileService(sl())); - sl.registerLazySingleton(() => InsightsService(sl())); - sl.registerLazySingleton(() => CalendarService(sl())); - sl.registerLazySingleton(() => SettingsService(sl())); - sl.registerLazySingleton(() => ConsultantService(sl())); - sl.registerLazySingleton(() => DiaryService(sl())); - sl.registerLazySingleton(() => GlossaryService(sl())); - sl.registerLazySingleton(() => BarcodeService(sl())); - sl.registerLazySingleton(() => DietService(sl())); - sl.registerLazySingleton(() => PlansService(sl())); - sl.registerLazySingleton(() => PlanService(sl())); - sl.registerLazySingleton(() => MyDietsService(sl())); - sl.registerLazySingleton(() => MyPlansService(sl())); - sl.registerLazySingleton(() => WsService(sl())); - sl.registerLazySingleton(() => AboutRecipeService(sl())); - sl.registerLazySingleton(() => ComplainingService(sl())); - sl.registerLazySingleton(() => AuthService(sl())); - sl.registerLazySingleton(() => CardsService(sl())); + sl.registerLazySingleton( + () => FeedService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ProfileService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => InsightsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CalendarService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => SettingsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ConsultantService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => DiaryService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => GlossaryService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BarcodeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => DietService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => PlansService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => PlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyDietsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyPlansService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton(() => WsService(sl(), errorLogger: sl())); + sl.registerLazySingleton( + () => AboutRecipeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ComplainingService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => AuthService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CardsService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton(() => ConsultationService(sl())); - sl.registerLazySingleton(() => CancelPlanService(sl())); - sl.registerLazySingleton(() => CreatePlanService(sl())); - sl.registerLazySingleton(() => NotificationsService(sl())); + sl.registerLazySingleton( + () => CancelPlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CreatePlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => NotificationsService(sl(), responseErrors: sl()), + ); sl.registerLazySingleton(() => FirebaseApi(errorReporter: sl())); sl.registerLazySingleton( () => VideoCallCallKitCoordinator(firebaseApi: sl()), @@ -94,23 +141,49 @@ class ServiceRegistrations { sl.registerLazySingleton( () => VideoCallSystemPipCoordinator(), ); - sl.registerLazySingleton(() => ResetPasswordService(sl())); - sl.registerLazySingleton(() => BlockedUserService(sl())); - sl.registerLazySingleton(() => CommentsService(sl())); - sl.registerLazySingleton(() => MyRecipesService(sl())); - sl.registerLazySingleton(() => ConsultantRatingService(sl())); - sl.registerLazySingleton(() => NotificationSettingsService(sl())); - sl.registerLazySingleton(() => ViewsService(sl())); + sl.registerLazySingleton( + () => ResetPasswordService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BlockedUserService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CommentsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyRecipesService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ConsultantRatingService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => NotificationSettingsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ViewsService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton(() => const SbpServiceImpl()); - sl.registerLazySingleton(() => PersonalDietSuggestionService(sl())); - sl.registerLazySingleton(() => RegistrationServiceV2(sl())); + sl.registerLazySingleton( + () => PersonalDietSuggestionService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => RegistrationServiceV2(sl(), errorLogger: sl()), + ); // Content services - sl.registerLazySingleton(() => CreateRecipeService(sl())); - sl.registerLazySingleton(() => BlogPostService(sl())); - sl.registerLazySingleton(() => CreateDietService(sl())); + sl.registerLazySingleton( + () => CreateRecipeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BlogPostService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CreateDietService(sl(), errorLogger: sl()), + ); // Auth services - sl.registerLazySingleton(() => RegistrationService(sl())); + sl.registerLazySingleton( + () => RegistrationService(sl(), errorLogger: sl()), + ); } } diff --git a/lib/core/error_reporting/api_response_dio.dart b/lib/core/error_reporting/api_response_dio.dart new file mode 100644 index 00000000..d9c51f9d --- /dev/null +++ b/lib/core/error_reporting/api_response_dio.dart @@ -0,0 +1,71 @@ +import 'package:dio/dio.dart'; +import 'package:dio/io.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; + +class ApiResponseDio extends DioForNative { + ApiResponseDio(BaseOptions super.options, this._responseErrors) { + transformer = _ApiResponseTransformer( + transformer, + _responseErrors, + _responseStatuses, + ); + } + + final ApiResponseErrorReporter _responseErrors; + final _responseStatuses = Expando(); + + @override + Future> fetch(RequestOptions requestOptions) async { + try { + return await super.fetch(requestOptions); + } on DioException catch (error) { + final cause = error.error; + final status = _responseStatuses[error.requestOptions]; + // Dio приводит тип корневого значения до вызова fromJson в Retrofit. + if (error.type == DioExceptionType.unknown && + error.requestOptions.responseType == ResponseType.json && + cause is TypeError && + status != null) { + _responseErrors.report( + error, + cause.stackTrace ?? error.stackTrace, + method: error.requestOptions.method, + statusCode: status, + ); + } + rethrow; + } + } +} + +class _ApiResponseTransformer implements Transformer { + _ApiResponseTransformer(this._delegate, this._responseErrors, this._statuses); + + final Transformer _delegate; + final ApiResponseErrorReporter _responseErrors; + final Expando _statuses; + + @override + Future transformRequest(RequestOptions options) => + _delegate.transformRequest(options); + + @override + Future transformResponse( + RequestOptions options, + ResponseBody response, + ) async { + try { + final data = await _delegate.transformResponse(options, response); + _statuses[options] = response.statusCode; + return data; + } on FormatException catch (error, stackTrace) { + _responseErrors.report( + error, + stackTrace, + method: options.method, + statusCode: response.statusCode, + ); + rethrow; + } + } +} diff --git a/lib/core/error_reporting/api_response_error_reporter.dart b/lib/core/error_reporting/api_response_error_reporter.dart new file mode 100644 index 00000000..54077d1e --- /dev/null +++ b/lib/core/error_reporting/api_response_error_reporter.dart @@ -0,0 +1,111 @@ +import 'dart:async'; +import 'dart:developer'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:retrofit/retrofit.dart'; + +class ApiResponseErrorReporter implements ParseErrorLogger { + ApiResponseErrorReporter(this._reporter); + + final ErrorReporter _reporter; + static final _capturedErrors = Expando(); + + static bool wasCaptured(Object error) => + _isCaptured(error) || (error is DioException && _isCaptured(error.error)); + + static bool _isCaptured(Object? error) => + error != null && + (error is Error || error is Exception) && + _capturedErrors[error] == true; + + static T decode( + ApiResponseErrorReporter? reporter, + Response response, + String endpoint, + T Function() parse, + ) { + try { + return parse(); + } catch (error, stackTrace) { + reporter?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: endpoint, + ); + rethrow; + } + } + + @override + void logError( + Object error, + StackTrace stackTrace, + RequestOptions options, { + Response? response, + }) { + report( + error, + stackTrace, + method: options.method, + statusCode: response?.statusCode, + ); + } + + void report( + Object error, + StackTrace stackTrace, { + required String method, + int? statusCode, + String? endpoint, + }) { + if (error is Error || error is Exception) { + _capturedErrors[error] = true; + } + // Сообщение исходного исключения может содержать значения из ответа API. + final cause = error is DioException ? error.error ?? error : error; + unawaited( + _send( + ApiResponseDecodeException(cause.runtimeType.toString()), + stackTrace, + { + 'http_method': method, + 'http_status_code': ?statusCode, + 'endpoint': ?endpoint, + }, + ), + ); + } + + Future _send( + ApiResponseDecodeException error, + StackTrace stackTrace, + Map context, + ) async { + try { + await _reporter.report( + error, + stackTrace, + origin: 'api_response', + extras: context, + ); + } catch (reportError, reportStackTrace) { + log( + 'Не удалось записать ошибку разбора ответа API', + error: reportError.runtimeType, + stackTrace: reportStackTrace, + ); + } + } +} + +class ApiResponseDecodeException implements Exception { + ApiResponseDecodeException(this.causeType); + + final String causeType; + + @override + String toString() => 'Could not decode API response ($causeType)'; +} diff --git a/lib/core/error_reporting/error_report_policy.dart b/lib/core/error_reporting/error_report_policy.dart index e2864af7..0bf81933 100644 --- a/lib/core/error_reporting/error_report_policy.dart +++ b/lib/core/error_reporting/error_report_policy.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/push/hms_client_error.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; @@ -14,6 +15,7 @@ class ErrorReportPolicy { /// When `false`, the error is not sent via [ErrorReporter]. static bool shouldReport(Object? error) { if (error == null) return false; + if (ApiResponseErrorReporter.wasCaptured(error)) return false; if (error is String) return false; if (error is SocketException) return false; if (isHmsClientUnavailable(error)) return false; @@ -34,11 +36,23 @@ class ErrorReportPolicy { final t = event.throwable; if (t == null) return true; if (t is DioException) { - return _allowSentrySdkDio(t); + return !ApiResponseErrorReporter.wasCaptured(t) && _allowSentrySdkDio(t); } return shouldReport(t); } + static SentryEvent? prepareSentryEvent(SentryEvent event, Hint hint) { + if (!allowSentryEvent(event, hint)) return null; + if (event.throwable is ApiResponseDecodeException) { + // HTTP breadcrumbs могут содержать идентификаторы в пути и параметры запроса. + event.breadcrumbs = event.breadcrumbs + ?.where((breadcrumb) => breadcrumb.category != 'http') + .toList(); + event.request = null; + } + return event; + } + /// Cancel, timeouts, socket / connection errors — do not send (noisy, often user environment). static bool _isTransientDioFailure(DioException e) { switch (e.type) { diff --git a/lib/core/routing/other_routes.dart b/lib/core/routing/other_routes.dart index f07247dd..f06f44ef 100644 --- a/lib/core/routing/other_routes.dart +++ b/lib/core/routing/other_routes.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:dio/dio.dart'; import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/prefs.dart'; @@ -103,7 +104,7 @@ class OtherRoutes { redirect: (context, state) async { try { // Проверка версии с таймаутом, чтобы не блокировать запуск приложения - final versions = await sl() + final response = await sl() .get('${sl().baseUrl}/api/app_versions') .timeout( const Duration(seconds: 5), @@ -111,12 +112,8 @@ class OtherRoutes { // При таймауте пропускаем проверку и идем дальше throw TimeoutException('Version check timeout'); }, - ) - .then((response) => response.data) - .catchError((e) { - // При любой ошибке пропускаем проверку версии - return null; - }); + ); + final versions = response.data; if (versions == null) { // Если проверка не удалась, пропускаем экран обновления @@ -126,7 +123,15 @@ class OtherRoutes { PackageInfo packageInfo = await PackageInfo.fromPlatform(); String version = packageInfo.version; Version currentVersion = Version.parse(version); - Version latestVersion = Version.parse(versions['min_version']); + final responseErrors = sl.isRegistered() + ? sl() + : null; + final latestVersion = ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/app_versions', + () => Version.parse(versions['min_version']), + ); if (latestVersion > currentVersion) { return null; } else { diff --git a/lib/core/views/service/views_service.dart b/lib/core/views/service/views_service.dart index e89990fa..fb0a3cef 100644 --- a/lib/core/views/service/views_service.dart +++ b/lib/core/views/service/views_service.dart @@ -6,7 +6,11 @@ part 'views_service.g.dart'; @RestApi() abstract class ViewsService { - factory ViewsService(Dio dio, {String baseUrl}) = _ViewsService; + factory ViewsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ViewsService; @POST('/api/views') Future viewContent({ diff --git a/lib/core/websockets/ws_service.dart b/lib/core/websockets/ws_service.dart index 92d326f0..4f962918 100644 --- a/lib/core/websockets/ws_service.dart +++ b/lib/core/websockets/ws_service.dart @@ -8,7 +8,11 @@ part 'ws_service.g.dart'; @RestApi() abstract class WsService { - factory WsService(Dio dio, {String baseUrl}) = _WsService; + factory WsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _WsService; @GET('/api/profile/ws/params') Future getWebsocket(); diff --git a/lib/features/auth/services/auth_service.dart b/lib/features/auth/services/auth_service.dart index 2c7c6249..0fe4c9df 100644 --- a/lib/features/auth/services/auth_service.dart +++ b/lib/features/auth/services/auth_service.dart @@ -12,7 +12,11 @@ part 'auth_service.g.dart'; @RestApi() abstract class AuthService { - factory AuthService(Dio dio, {String? baseUrl}) = _AuthService; + factory AuthService( + Dio dio, { + String? baseUrl, + ParseErrorLogger? errorLogger, + }) = _AuthService; @POST('/api/login') Future getTokenByCredentials({@Body() required CredentialsModel credentials}); diff --git a/lib/features/auth/services/reset_password_service.dart b/lib/features/auth/services/reset_password_service.dart index 9a7a101d..8343468e 100644 --- a/lib/features/auth/services/reset_password_service.dart +++ b/lib/features/auth/services/reset_password_service.dart @@ -5,7 +5,11 @@ part 'reset_password_service.g.dart'; @RestApi() abstract class ResetPasswordService { - factory ResetPasswordService(Dio dio, {String baseUrl}) = _ResetPasswordService; + factory ResetPasswordService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ResetPasswordService; @POST('/api/send_password_reset_code') Future sendEmailCodeForPasswordChange({ diff --git a/lib/features/barcode/services/barcode_service.dart b/lib/features/barcode/services/barcode_service.dart index e64e2575..31990b1c 100644 --- a/lib/features/barcode/services/barcode_service.dart +++ b/lib/features/barcode/services/barcode_service.dart @@ -1,24 +1,28 @@ -import 'package:dio/dio.dart'; -import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart'; -import 'package:retrofit/retrofit.dart'; - -part 'barcode_service.g.dart'; - -@RestApi() -abstract class BarcodeService { - factory BarcodeService(Dio dio, {String baseUrl}) = _BarcodeService; - - @GET('/api/gsone/barcode/{barcode}') - Future getProductByBarcode({@Path('barcode') required String barcode}); - - @GET('/api/gsone/barcode/status/{task_id}') - Future getTaskStatus({@Path('task_id') required String taskId}); -} - - - - - - - - +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'barcode_service.g.dart'; + +@RestApi() +abstract class BarcodeService { + factory BarcodeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BarcodeService; + + @GET('/api/gsone/barcode/{barcode}') + Future getProductByBarcode({@Path('barcode') required String barcode}); + + @GET('/api/gsone/barcode/status/{task_id}') + Future getTaskStatus({@Path('task_id') required String taskId}); +} + + + + + + + + diff --git a/lib/features/blog_post_create/services/blog_post_service.dart b/lib/features/blog_post_create/services/blog_post_service.dart index 72c0be12..eadb029b 100644 --- a/lib/features/blog_post_create/services/blog_post_service.dart +++ b/lib/features/blog_post_create/services/blog_post_service.dart @@ -5,7 +5,11 @@ part 'blog_post_service.g.dart'; @RestApi() abstract class BlogPostService { - factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService; + factory BlogPostService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BlogPostService; @POST('/api/v2/blogPosts/create/published') @MultiPart() diff --git a/lib/features/calendar/services/calendar_service.dart b/lib/features/calendar/services/calendar_service.dart index 2974f735..b2243f21 100644 --- a/lib/features/calendar/services/calendar_service.dart +++ b/lib/features/calendar/services/calendar_service.dart @@ -6,7 +6,11 @@ part 'calendar_service.g.dart'; @RestApi() abstract class CalendarService { - factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService; + factory CalendarService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CalendarService; @GET('/api/calendar/index') Future> getCalendar(); diff --git a/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart b/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart index ae677280..e7e18499 100644 --- a/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart +++ b/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart @@ -6,7 +6,11 @@ part 'cancel_plan_service.g.dart'; @RestApi() abstract class CancelPlanService { - factory CancelPlanService(Dio dio, {String baseUrl}) = _CancelPlanService; + factory CancelPlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CancelPlanService; @POST('/api/chosen_plans/{id}/cancel') Future cancelChosenPlan({ diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index 3bd6a505..e51fcf8a 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -17,7 +17,11 @@ part 'chat_service.g.dart'; @RestApi() abstract class ChatService { - factory ChatService(Dio dio, {String baseUrl}) = _ChatService; + factory ChatService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ChatService; @GET('/api/v2/chat/index') Future getChatRooms({ diff --git a/lib/features/complaining/services/complaining_service.dart b/lib/features/complaining/services/complaining_service.dart index 276ac750..90fb78b2 100644 --- a/lib/features/complaining/services/complaining_service.dart +++ b/lib/features/complaining/services/complaining_service.dart @@ -6,7 +6,11 @@ part 'complaining_service.g.dart'; @RestApi() abstract class ComplainingService { - factory ComplainingService(Dio dio, {String baseUrl}) = _ComplainingService; + factory ComplainingService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ComplainingService; @POST('/api/plans/{slug}/complain/{category}') Future sendPlanComplain({ diff --git a/lib/features/consultant/become_consultant/services/consultant_service.dart b/lib/features/consultant/become_consultant/services/consultant_service.dart index 8458824d..2ab5f553 100644 --- a/lib/features/consultant/become_consultant/services/consultant_service.dart +++ b/lib/features/consultant/become_consultant/services/consultant_service.dart @@ -9,7 +9,11 @@ part 'consultant_service.g.dart'; @RestApi() abstract class ConsultantService { - factory ConsultantService(Dio dio, {String baseUrl}) = _ConsultantService; + factory ConsultantService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ConsultantService; @POST('/api/v2/consultant_request/registration') Future consultantRegistration({ diff --git a/lib/features/consultant_rating/services/consultant_rating_service.dart b/lib/features/consultant_rating/services/consultant_rating_service.dart index c4412afb..a824f457 100644 --- a/lib/features/consultant_rating/services/consultant_rating_service.dart +++ b/lib/features/consultant_rating/services/consultant_rating_service.dart @@ -8,7 +8,11 @@ part 'consultant_rating_service.g.dart'; @RestApi() abstract class ConsultantRatingService { - factory ConsultantRatingService(Dio dio, {String baseUrl}) = _ConsultantRatingService; + factory ConsultantRatingService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ConsultantRatingService; @GET('/api/consultants/rating/statistics') Future getConsultantStatistics({@Query('filters[duration][\$gte]') String? date}); diff --git a/lib/features/create_diet/services/create_diet_service.dart b/lib/features/create_diet/services/create_diet_service.dart index cc010293..e97d418a 100644 --- a/lib/features/create_diet/services/create_diet_service.dart +++ b/lib/features/create_diet/services/create_diet_service.dart @@ -6,7 +6,11 @@ part 'create_diet_service.g.dart'; @RestApi() abstract class CreateDietService { - factory CreateDietService(Dio dio, {String baseUrl}) = _CreateDietService; + factory CreateDietService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreateDietService; @POST('/api/diets/create/published') @MultiPart() diff --git a/lib/features/create_plan/services/create_plan_service.dart b/lib/features/create_plan/services/create_plan_service.dart index cafcba2f..9a10e6fa 100644 --- a/lib/features/create_plan/services/create_plan_service.dart +++ b/lib/features/create_plan/services/create_plan_service.dart @@ -5,7 +5,11 @@ part 'create_plan_service.g.dart'; @RestApi() abstract class CreatePlanService { - factory CreatePlanService(Dio dio, {String baseUrl}) = _CreatePlanService; + factory CreatePlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreatePlanService; @POST('/api/plans/create/published') @MultiPart() diff --git a/lib/features/create_recipe/services/recipe_service.dart b/lib/features/create_recipe/services/recipe_service.dart index 4bed540a..0bd6e0f9 100644 --- a/lib/features/create_recipe/services/recipe_service.dart +++ b/lib/features/create_recipe/services/recipe_service.dart @@ -8,7 +8,11 @@ part 'recipe_service.g.dart'; @RestApi() abstract class CreateRecipeService { - factory CreateRecipeService(Dio dio, {String baseUrl}) = _CreateRecipeService; + factory CreateRecipeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreateRecipeService; @POST('/api/recipes/{slug}/like') Future likeRecipe({ diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 985fb885..656009e1 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -13,7 +13,11 @@ part 'diary_service.g.dart'; @RestApi() abstract class DiaryService { - factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; + factory DiaryService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _DiaryService; @GET('/api/diary/index/{date}') Future> getDiaryIndexByDate({@Path('date') required String date}); diff --git a/lib/features/diets/services/diet_service.dart b/lib/features/diets/services/diet_service.dart index b25b8054..b4c7e509 100644 --- a/lib/features/diets/services/diet_service.dart +++ b/lib/features/diets/services/diet_service.dart @@ -7,7 +7,11 @@ part 'diet_service.g.dart'; @RestApi() abstract class DietService { - factory DietService(Dio dio, {String baseUrl}) = _DietService; + factory DietService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _DietService; @POST('/api/diets/{id}/like') Future likeDiet({ diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index 22a453be..90b35e2f 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -14,7 +14,11 @@ part 'feed_service.g.dart'; @RestApi() abstract class FeedService { - factory FeedService(Dio dio, {String baseUrl}) = _FeedService; + factory FeedService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _FeedService; @GET('/api/blogPosts/index') Future getBlogPostList({@Query('page') required int page, @Query('query_search') String? query}); diff --git a/lib/features/glossary/services/glossary_service.dart b/lib/features/glossary/services/glossary_service.dart index 8c28bb16..1ed4783d 100644 --- a/lib/features/glossary/services/glossary_service.dart +++ b/lib/features/glossary/services/glossary_service.dart @@ -6,7 +6,11 @@ part 'glossary_service.g.dart'; @RestApi() abstract class GlossaryService { - factory GlossaryService(Dio dio, {String baseUrl}) = _GlossaryService; + factory GlossaryService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _GlossaryService; @GET('/api/glossaries/search') Future getGlossaryByQuery({ diff --git a/lib/features/insights/services/insights_service.dart b/lib/features/insights/services/insights_service.dart index f0e64028..c7fe04b6 100644 --- a/lib/features/insights/services/insights_service.dart +++ b/lib/features/insights/services/insights_service.dart @@ -9,7 +9,11 @@ part 'insights_service.g.dart'; /// недоступный профиль — 403. @RestApi() abstract class InsightsService { - factory InsightsService(Dio dio, {String baseUrl}) = _InsightsService; + factory InsightsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _InsightsService; /// Свои графики целиком. @GET('/api/profile/insights') diff --git a/lib/features/menu/services/blocked_users_service.dart b/lib/features/menu/services/blocked_users_service.dart index 6a4ed987..a6ed6b13 100644 --- a/lib/features/menu/services/blocked_users_service.dart +++ b/lib/features/menu/services/blocked_users_service.dart @@ -6,7 +6,11 @@ part 'blocked_users_service.g.dart'; @RestApi() abstract class BlockedUserService { - factory BlockedUserService(Dio dio, {String baseUrl}) = _BlockedUserService; + factory BlockedUserService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BlockedUserService; @GET('/api/blocked_users') Future getBlockedUsers(); diff --git a/lib/features/menu/services/notification_settings_service.dart b/lib/features/menu/services/notification_settings_service.dart index f489267f..ee08e819 100644 --- a/lib/features/menu/services/notification_settings_service.dart +++ b/lib/features/menu/services/notification_settings_service.dart @@ -6,7 +6,11 @@ part 'notification_settings_service.g.dart'; @RestApi() abstract class NotificationSettingsService { - factory NotificationSettingsService(Dio dio, {String baseUrl}) = _NotificationSettingsService; + factory NotificationSettingsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _NotificationSettingsService; @GET('/api/profile/notification_settings') Future getNotificationSettings(); diff --git a/lib/features/my_diets/services/my_diets_service.dart b/lib/features/my_diets/services/my_diets_service.dart index 41e3174f..b7224b10 100644 --- a/lib/features/my_diets/services/my_diets_service.dart +++ b/lib/features/my_diets/services/my_diets_service.dart @@ -7,7 +7,11 @@ part 'my_diets_service.g.dart'; @RestApi() abstract class MyDietsService { - factory MyDietsService(Dio dio, {String baseUrl}) = _MyDietsService; + factory MyDietsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyDietsService; @GET('/api/profile/my_diets') Future getDiets({ diff --git a/lib/features/my_finance/services/cards_service.dart b/lib/features/my_finance/services/cards_service.dart index c653d1a5..e051968b 100644 --- a/lib/features/my_finance/services/cards_service.dart +++ b/lib/features/my_finance/services/cards_service.dart @@ -7,7 +7,11 @@ part 'cards_service.g.dart'; @RestApi() abstract class CardsService { - factory CardsService(Dio dio, {String baseUrl}) = _CardsService; + factory CardsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CardsService; @GET('/api/finances/cards') Future> getCards(); diff --git a/lib/features/my_plans/services/my_plans_service.dart b/lib/features/my_plans/services/my_plans_service.dart index bc24aec8..4eb15dd8 100644 --- a/lib/features/my_plans/services/my_plans_service.dart +++ b/lib/features/my_plans/services/my_plans_service.dart @@ -6,7 +6,11 @@ part 'my_plans_service.g.dart'; @RestApi() abstract class MyPlansService { - factory MyPlansService(Dio dio, {String baseUrl}) = _MyPlansService; + factory MyPlansService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyPlansService; @GET('/api/profile/my_plans') Future getPlans({ diff --git a/lib/features/notifications/service/notifications_service.dart b/lib/features/notifications/service/notifications_service.dart index dbe2d16c..9d815647 100644 --- a/lib/features/notifications/service/notifications_service.dart +++ b/lib/features/notifications/service/notifications_service.dart @@ -1,13 +1,17 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/features/notifications/models/notification_model.dart'; class NotificationsService { final Dio dio; - NotificationsService(this.dio); + final ApiResponseErrorReporter? responseErrors; + static const _endpoint = '/api/profile/notifications'; + + NotificationsService(this.dio, {this.responseErrors}); Future?> getNotifications({required int page}) async { + final response = await dio.get('$_endpoint?page=$page'); try { - final response = await dio.get('/api/profile/notifications?page=$page'); if (response.statusCode == 200) { final data = response.data['data'] as List; @@ -493,7 +497,14 @@ class NotificationsService { ), NotificationType.unknown => UnknownNotification(type: type, createdAt: parseDate(createdAt)), }; - } catch (e) { + } catch (error, stackTrace) { + responseErrors?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: _endpoint, + ); return UnknownNotification(type: NotificationType.unknown, createdAt: DateTime.now()); } }).toList(); @@ -510,7 +521,14 @@ class NotificationsService { }; } return null; - } catch (e) { + } catch (error, stackTrace) { + responseErrors?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: _endpoint, + ); rethrow; } } diff --git a/lib/features/payment/repositories/payment_repository.dart b/lib/features/payment/repositories/payment_repository.dart index 00d2ca75..82736126 100644 --- a/lib/features/payment/repositories/payment_repository.dart +++ b/lib/features/payment/repositories/payment_repository.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/features/chat/models/payment_model.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; import 'package:eatvio_app/features/payment/models/promo_applied_list_response.dart'; @@ -10,8 +11,9 @@ import 'package:eatvio_app/features/payment/models/promo_validate_response.dart' /// Репозиторий оплаты консультаций (chosen_plan) через Alfa Bank / СБП. class PaymentRepository { final ChatService chatService; + final ApiResponseErrorReporter? responseErrors; - PaymentRepository({required this.chatService}); + PaymentRepository({required this.chatService, this.responseErrors}); /// Запускает процесс оплаты: POST `/api/chosen_plans/{id}/start_payment_process` /// с `payment_provider: alfa-bank`. @@ -64,9 +66,15 @@ class PaymentRepository { body: {'promo_code': promoCode}, ); } on DioException catch (e) { - final data = e.response?.data; - if (data is Map) { - return PromoApplyResponse.fromJson(data); + final response = e.response; + final data = response?.data; + if (response != null && data is Map) { + return ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/chosen_plans/{id}/apply_promo', + () => PromoApplyResponse.fromJson(data), + ); } rethrow; } @@ -77,9 +85,15 @@ class PaymentRepository { try { return await chatService.removePromoCode(id: planId); } on DioException catch (e) { - final data = e.response?.data; - if (data is Map) { - return PromoRemoveResponse.fromJson(data); + final response = e.response; + final data = response?.data; + if (response != null && data is Map) { + return ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/chosen_plans/{id}/remove_promo_code', + () => PromoRemoveResponse.fromJson(data), + ); } rethrow; } diff --git a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart index 245cbdbd..db9be06d 100644 --- a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart +++ b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart @@ -6,8 +6,11 @@ part 'personal_diet_suggestion_service.g.dart'; @RestApi() abstract class PersonalDietSuggestionService { - factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) = - _PersonalDietSuggestionService; + factory PersonalDietSuggestionService( + Dio dio, { + String? baseUrl, + ParseErrorLogger? errorLogger, + }) = _PersonalDietSuggestionService; @GET('/api/consultations') Future getConsultationWithPersonalDiets({ diff --git a/lib/features/plans/services/plan_service.dart b/lib/features/plans/services/plan_service.dart index 8a179760..6a7105c6 100644 --- a/lib/features/plans/services/plan_service.dart +++ b/lib/features/plans/services/plan_service.dart @@ -7,7 +7,11 @@ part 'plan_service.g.dart'; @RestApi() abstract class PlanService { - factory PlanService(Dio dio, {String baseUrl}) = _PlanService; + factory PlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _PlanService; @GET('/api/plans/show/{slug}') Future getPlan(@Path('slug') String slug); diff --git a/lib/features/plans/services/plans_service.dart b/lib/features/plans/services/plans_service.dart index 5f8769ce..10d4257d 100644 --- a/lib/features/plans/services/plans_service.dart +++ b/lib/features/plans/services/plans_service.dart @@ -6,7 +6,11 @@ part 'plans_service.g.dart'; @RestApi() abstract class PlansService { - factory PlansService(Dio dio, {String baseUrl}) = _PlansService; + factory PlansService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _PlansService; @GET('/api/plans/get_by_author/{author}') Future getPlansBySlug({ diff --git a/lib/features/profile/services/profile_service.dart b/lib/features/profile/services/profile_service.dart index 95117d36..60910256 100644 --- a/lib/features/profile/services/profile_service.dart +++ b/lib/features/profile/services/profile_service.dart @@ -14,7 +14,11 @@ part 'profile_service.g.dart'; @RestApi() abstract class ProfileService { - factory ProfileService(Dio dio, {String baseUrl}) = _ProfileService; + factory ProfileService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ProfileService; @GET('/api/profile/show/{slug}') Future getProfileBySlug({@Path() required String slug}); diff --git a/lib/features/recipe/services/about_recipe_service.dart b/lib/features/recipe/services/about_recipe_service.dart index 21170ed4..b1edadbb 100644 --- a/lib/features/recipe/services/about_recipe_service.dart +++ b/lib/features/recipe/services/about_recipe_service.dart @@ -6,7 +6,11 @@ part 'about_recipe_service.g.dart'; @RestApi() abstract class AboutRecipeService { - factory AboutRecipeService(Dio dio, {String baseUrl}) = _AboutRecipeService; + factory AboutRecipeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _AboutRecipeService; @POST('/api/recipes/{slug}/like') Future likeRecipe({ diff --git a/lib/features/recipe/services/my_recipes_service.dart b/lib/features/recipe/services/my_recipes_service.dart index 7500edcb..436debae 100644 --- a/lib/features/recipe/services/my_recipes_service.dart +++ b/lib/features/recipe/services/my_recipes_service.dart @@ -6,7 +6,11 @@ part 'my_recipes_service.g.dart'; @RestApi() abstract class MyRecipesService { - factory MyRecipesService(Dio dio, {String baseUrl}) = _MyRecipesService; + factory MyRecipesService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyRecipesService; @GET('/api/recipes/my') Future getMyRecipes(); diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index 200c2f6f..c1b1b752 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -6,7 +6,11 @@ part 'registration_service.g.dart'; @RestApi() abstract class RegistrationService { - factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; + factory RegistrationService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _RegistrationService; @POST('/api/register') Future> register({ diff --git a/lib/features/registration_v2/services/registration_service_v2.dart b/lib/features/registration_v2/services/registration_service_v2.dart index 2472eb40..53a0bfbf 100644 --- a/lib/features/registration_v2/services/registration_service_v2.dart +++ b/lib/features/registration_v2/services/registration_service_v2.dart @@ -5,7 +5,11 @@ part 'registration_service_v2.g.dart'; @RestApi() abstract class RegistrationServiceV2 { - factory RegistrationServiceV2(Dio dio, {String baseUrl}) = _RegistrationServiceV2; + factory RegistrationServiceV2( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _RegistrationServiceV2; @POST('/api/register') Future> register({ diff --git a/lib/features/settings/services/settings_service.dart b/lib/features/settings/services/settings_service.dart index c83f4c41..c35e617c 100644 --- a/lib/features/settings/services/settings_service.dart +++ b/lib/features/settings/services/settings_service.dart @@ -9,7 +9,11 @@ part 'settings_service.g.dart'; @RestApi() abstract class SettingsService { - factory SettingsService(Dio dio, {String baseUrl}) = _SettingsService; + factory SettingsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _SettingsService; @GET('/api/profile/settings') Future getProfileSettings(); diff --git a/lib/features/video_calls/services/video_call_service.dart b/lib/features/video_calls/services/video_call_service.dart index 88768381..530c9ab2 100644 --- a/lib/features/video_calls/services/video_call_service.dart +++ b/lib/features/video_calls/services/video_call_service.dart @@ -7,7 +7,11 @@ part 'video_call_service.g.dart'; @RestApi() abstract class VideoCallService { - factory VideoCallService(Dio dio, {String baseUrl}) = _VideoCallService; + factory VideoCallService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _VideoCallService; @GET('/api/v2/chat/{conversation}/video-call/token') Future getParticipantToken({ diff --git a/lib/main.dart b/lib/main.dart index bbc8e5d4..4a2c77fd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -16,13 +16,14 @@ import 'package:flutter_portal/flutter_portal.dart'; import 'package:keyboard_dismisser/keyboard_dismisser.dart'; Future main() async { - WidgetsFlutterBinding.ensureInitialized(); - FlutterForegroundTask.initCommunicationPort(); - VideoCallForegroundBootstrap.ensureInitialized(); - await AppInitializer.initialize(buildType: AppBuildType.prod); - await sl().initialize(); - await PushNavigationHandler.initialize(); - await AppInitializer.runAppWithSentry(() => runApp(const MyApp())); + await AppInitializer.runAppWithSentry(() async { + FlutterForegroundTask.initCommunicationPort(); + VideoCallForegroundBootstrap.ensureInitialized(); + await AppInitializer.initialize(buildType: AppBuildType.prod); + await sl().initialize(); + await PushNavigationHandler.initialize(); + runApp(const MyApp()); + }); } class MyApp extends StatefulWidget { diff --git a/test/core/error_reporting/api_response_reporting_test.dart b/test/core/error_reporting/api_response_reporting_test.dart new file mode 100644 index 00000000..ad19d30d --- /dev/null +++ b/test/core/error_reporting/api_response_reporting_test.dart @@ -0,0 +1,311 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/di/app_config_registration.dart'; +import 'package:eatvio_app/core/di/external_registrations.dart'; +import 'package:eatvio_app/core/di/repository_registrations.dart'; +import 'package:eatvio_app/core/di/service_registrations.dart'; +import 'package:eatvio_app/core/error_reporting/error_report_policy.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:eatvio_app/core/routing/other_routes.dart'; +import 'package:eatvio_app/core/routing/route_constants.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; +import 'package:eatvio_app/features/notifications/service/notifications_service.dart'; +import 'package:eatvio_app/features/payment/repositories/payment_repository.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart'; +import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_state.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _MemoryTransport transport; + late List events; + + setUp(() async { + transport = _MemoryTransport(); + events = []; + await Sentry.init((options) { + options.dsn = 'https://test@example.invalid/1'; + options.transport = transport; + options.sendClientReports = false; + // Проверяем дедупликацию в приложении независимо от кеша SDK. + options.enableDeduplication = false; + options.beforeSend = (event, hint) { + final prepared = ErrorReportPolicy.prepareSentryEvent(event, hint); + if (prepared != null) events.add(prepared); + return prepared; + }; + }); + + dotenv.loadFromString( + envString: 'DEV_BASE_URL=https://api.example.invalid', + ); + SharedPreferences.setMockInitialValues({ + PrefsKeys.welcomeScreenWasShowed.name: true, + 'token': 'synthetic-token', + }); + AppConfigRegistration.registerAppConfig(buildType: AppBuildType.tests); + ExternalRegistrations.registerAll(); + ServiceRegistrations.registerAll(); + RepositoryRegistrations.registerAll(); + }); + + tearDown(() async { + TokenStorage.clearCache(); + await sl.reset(); + await Sentry.close(); + }); + + test( + 'reports a missing recipe field once and keeps the original stack', + () async { + sl().httpClientAdapter = _ResponseAdapter(200, '{}'); + final cubit = AboutRecipeCubit( + recipeRepository: sl(), + profileRepository: sl(), + ); + addTearDown(cubit.close); + + await cubit.initRecipe('private-recipe-id'); + await transport.waitForEvent(); + + expect(cubit.state, isA()); + expect(events.single.tags?['origin'], 'api_response'); + expect( + events.single.exceptions!.single.stackTrace!.frames.any( + (frame) => frame.fileName?.endsWith('recipes_model.g.dart') ?? false, + ), + isTrue, + ); + expect(transport.sent, hasLength(1)); + }, + ); + + test( + 'reports a malformed profile even when the welcome redirect handles it', + () async { + final adapter = _ResponseAdapter(200, '{}'); + sl().httpClientAdapter = adapter; + final route = OtherRoutes.createRoutes().whereType().singleWhere( + (route) => route.path == RouteConstants.welcomeScreen, + ); + + expect( + await route.redirect!(_BuildContext(), _RouterState()), + RouteConstants.authScreen, + ); + await transport.waitForEvent(); + + expect(adapter.requests.single.path, '/api/profile/index'); + expect(events.single.exceptions!.single.value, contains('TypeError')); + expect(transport.sent, hasLength(1)); + }, + ); + + test( + 'reports invalid JSON without sending its contents or HTTP breadcrumbs', + () async { + const secret = 'private-patient-data'; + sl().httpClientAdapter = _ResponseAdapter(200, '{"$secret":'); + await Sentry.addBreadcrumb( + Breadcrumb.http( + url: Uri.parse('https://api.example.invalid/user/$secret'), + method: 'GET', + httpQuery: 'profile=$secret', + ), + ); + + await expectLater( + sl().getMyProfile(), + throwsA(isA()), + ); + await transport.waitForEvent(); + + final event = events.single; + expect(event.exceptions!.single.value, contains('FormatException')); + expect(event.exceptions!.single.stackTrace!.frames, isNotEmpty); + expect(event.tags?['origin'], 'api_response'); + expect( + event.contexts['report_extras'], + containsPair('http_status_code', '200'), + ); + expect(jsonEncode(event.toJson()), isNot(contains(secret))); + }, + ); + + test( + 'reports the wrong JSON root type before the Retrofit model parser', + () async { + sl().httpClientAdapter = _ResponseAdapter(200, '[]'); + + await expectLater( + sl().getMyProfile(), + throwsA(isA()), + ); + await transport.waitForEvent(); + + expect(events.single.exceptions!.single.value, contains('TypeError')); + expect( + events.single.contexts['report_extras'], + containsPair('http_status_code', '200'), + ); + }, + ); + + test( + 'reports a malformed notification and keeps the replacement item', + () async { + sl().httpClientAdapter = _ResponseAdapter( + 200, + '{"data":[17],"current_page":1,"last_page":1,"per_page":20,"total":1}', + ); + + final result = await sl().getNotifications(page: 1); + await transport.waitForEvent(); + + expect( + (result!['notifications'] as List).single, + isA(), + ); + expect( + events.single.contexts['report_extras'], + containsPair('endpoint', '/api/profile/notifications'), + ); + }, + ); + + test( + 'reports an invalid minimum version and still skips the update screen', + () async { + PackageInfo.setMockInitialValues( + appName: 'Eatvio', + packageName: 'example.invalid', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + sl().httpClientAdapter = _ResponseAdapter( + 200, + '{"min_version":"invalid"}', + ); + final route = OtherRoutes.createRoutes().whereType().singleWhere( + (route) => route.path == RouteConstants.updateScreen, + ); + + expect( + await route.redirect!(_BuildContext(), _RouterState()), + RouteConstants.welcomeScreen, + ); + await transport.waitForEvent(); + + expect( + events.single.contexts['report_extras'], + containsPair('endpoint', '/api/app_versions'), + ); + }, + ); + + test( + 'reports a malformed 422 promo response after its manual parse', + () async { + sl().httpClientAdapter = _ResponseAdapter(422, '{}'); + + await expectLater( + sl().applyPromoCode( + planId: 42, + promoCode: 'private', + ), + throwsA(isA()), + ); + await transport.waitForEvent(); + + expect( + events.single.contexts['report_extras'], + containsPair('http_status_code', '422'), + ); + expect(transport.sent, hasLength(1)); + }, + ); + + test('keeps expected 4xx quiet and captures a regular 5xx once', () async { + final dio = sl(); + final cubit = AboutRecipeCubit( + recipeRepository: sl(), + profileRepository: sl(), + ); + addTearDown(cubit.close); + + dio.httpClientAdapter = _ResponseAdapter(404, '{}'); + await cubit.initRecipe('synthetic'); + expect(events, isEmpty); + + dio.httpClientAdapter = _ResponseAdapter(500, '{}'); + await cubit.initRecipe('synthetic'); + await transport.waitForEvent(); + + expect( + events.single.exceptions!.first.mechanism!.type, + 'SentryDioClientAdapter', + ); + expect(transport.sent, hasLength(1)); + }); +} + +class _ResponseAdapter implements HttpClientAdapter { + _ResponseAdapter(this.statusCode, this.body); + + final int statusCode; + final String body; + final requests = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + return ResponseBody.fromString( + body, + statusCode, + headers: { + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} + +class _MemoryTransport implements Transport { + final sent = []; + final _firstEvent = Completer(); + + Future waitForEvent() => + _firstEvent.future.timeout(const Duration(seconds: 2)); + + @override + Future send(SentryEnvelope envelope) async { + sent.add(envelope); + if (!_firstEvent.isCompleted) _firstEvent.complete(); + return envelope.header.eventId; + } +} + +class _BuildContext extends Fake implements BuildContext {} + +class _RouterState extends Fake implements GoRouterState {}