fixed sentry crashes handling

This commit is contained in:
misha
2026-11-20 14:24:20 +03:00
parent 1e8c1ab2eb
commit 5308c11ca6
48 changed files with 909 additions and 136 deletions

View File

@@ -18,21 +18,22 @@ class AppInitializer {
static Future<void> initialize({required AppBuildType buildType}) async {
await _initializeEnvironment();
await _initializeDependencyInjection(buildType: buildType);
await _initializeSentry();
_preserveSplash();
await _initializeFirebase();
await _initializeDebugMode();
await _initializeAnalytics();
}
/// Инициализация Sentry
static Future<void> _initializeSentry() async {
static void _preserveSplash() {
final widgetsBinding = SentryWidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
}
/// Загрузка переменных окружения
static Future<void> _initializeEnvironment() async {
await dotenv.load(fileName: ".env");
if (!dotenv.isInitialized) {
await dotenv.load(fileName: '.env');
}
}
/// Инициализация Firebase
@@ -64,20 +65,25 @@ class AppInitializer {
/// Инициализация аналитики
static Future<void> _initializeAnalytics() async {
AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey));
AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey, flutterCrashReporting: false));
AppMetrica.reportEvent('Application started');
}
/// Запуск приложения с Sentry
static Future<void> runAppWithSentry(VoidCallback appRunner) async {
static Future<void> runAppWithSentry(
FutureOr<void> 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);
}

View File

@@ -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<void> deleteComment(@Path('id') int id);

View File

@@ -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<ErrorReporter>(SentryErrorReporter.new);
sl.registerLazySingleton(() => ApiResponseErrorReporter(sl()));
_registerDio();
_registerPrefs();
}
/// Регистрация Dio HTTP клиента
static void _registerDio() {
sl.registerLazySingleton(
() => Dio(
sl.registerLazySingleton<Dio>(
() => ApiResponseDio(
BaseOptions(
baseUrl: sl<AppConfig>().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()],

View File

@@ -86,7 +86,9 @@ class RepositoryRegistrations {
sl.registerLazySingleton<CommentsRepository>(() => CommentsRepository(service: sl()));
sl.registerLazySingleton<NotificationSettingsRepository>(() => NotificationSettingsRepository(sl()));
sl.registerLazySingleton<SbpRepository>(() => SbpRepository(sbpService: sl()));
sl.registerLazySingleton<PaymentRepository>(() => PaymentRepository(chatService: sl()));
sl.registerLazySingleton<PaymentRepository>(
() => PaymentRepository(chatService: sl(), responseErrors: sl()),
);
sl.registerLazySingleton<PersonalDietSuggestionRepository>(() => PersonalDietSuggestionRepository(personalDietSuggestionService: sl()));
sl.registerLazySingleton<RegistrationRepositoryV2>(() => RegistrationRepositoryV2(registrationService: sl()));

View File

@@ -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>(() => ChatService(sl()));
sl.registerLazySingleton<VideoCallService>(() => VideoCallService(sl()));
sl.registerLazySingleton<ChatService>(
() => ChatService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<VideoCallService>(
() => VideoCallService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<PublicDownloadsSaver>(
() => const PublicDownloadsSaver(),
);
sl.registerLazySingleton<VideoCallRecordingFileService>(
() => VideoCallRecordingFileService(dio: sl(), downloadsSaver: sl()),
);
sl.registerLazySingleton<FeedService>(() => FeedService(sl()));
sl.registerLazySingleton<ProfileService>(() => ProfileService(sl()));
sl.registerLazySingleton<InsightsService>(() => InsightsService(sl()));
sl.registerLazySingleton<CalendarService>(() => CalendarService(sl()));
sl.registerLazySingleton<SettingsService>(() => SettingsService(sl()));
sl.registerLazySingleton<ConsultantService>(() => ConsultantService(sl()));
sl.registerLazySingleton<DiaryService>(() => DiaryService(sl()));
sl.registerLazySingleton<GlossaryService>(() => GlossaryService(sl()));
sl.registerLazySingleton<BarcodeService>(() => BarcodeService(sl()));
sl.registerLazySingleton<DietService>(() => DietService(sl()));
sl.registerLazySingleton<PlansService>(() => PlansService(sl()));
sl.registerLazySingleton<PlanService>(() => PlanService(sl()));
sl.registerLazySingleton<MyDietsService>(() => MyDietsService(sl()));
sl.registerLazySingleton<MyPlansService>(() => MyPlansService(sl()));
sl.registerLazySingleton<WsService>(() => WsService(sl()));
sl.registerLazySingleton<AboutRecipeService>(() => AboutRecipeService(sl()));
sl.registerLazySingleton<ComplainingService>(() => ComplainingService(sl()));
sl.registerLazySingleton<AuthService>(() => AuthService(sl()));
sl.registerLazySingleton<CardsService>(() => CardsService(sl()));
sl.registerLazySingleton<FeedService>(
() => FeedService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ProfileService>(
() => ProfileService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<InsightsService>(
() => InsightsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<CalendarService>(
() => CalendarService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<SettingsService>(
() => SettingsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ConsultantService>(
() => ConsultantService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<DiaryService>(
() => DiaryService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<GlossaryService>(
() => GlossaryService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<BarcodeService>(
() => BarcodeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<DietService>(
() => DietService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<PlansService>(
() => PlansService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<PlanService>(
() => PlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<MyDietsService>(
() => MyDietsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<MyPlansService>(
() => MyPlansService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<WsService>(() => WsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()));
sl.registerLazySingleton<AboutRecipeService>(
() => AboutRecipeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ComplainingService>(
() => ComplainingService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<AuthService>(
() => AuthService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<CardsService>(
() => CardsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ConsultationService>(() => ConsultationService(sl()));
sl.registerLazySingleton<CancelPlanService>(() => CancelPlanService(sl()));
sl.registerLazySingleton<CreatePlanService>(() => CreatePlanService(sl()));
sl.registerLazySingleton<NotificationsService>(() => NotificationsService(sl()));
sl.registerLazySingleton<CancelPlanService>(
() => CancelPlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<CreatePlanService>(
() => CreatePlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<NotificationsService>(
() => NotificationsService(sl(), responseErrors: sl()),
);
sl.registerLazySingleton<FirebaseApi>(() => FirebaseApi(errorReporter: sl()));
sl.registerLazySingleton<VideoCallCallKitCoordinator>(
() => VideoCallCallKitCoordinator(firebaseApi: sl()),
@@ -94,23 +141,49 @@ class ServiceRegistrations {
sl.registerLazySingleton<VideoCallSystemPipCoordinator>(
() => VideoCallSystemPipCoordinator(),
);
sl.registerLazySingleton<ResetPasswordService>(() => ResetPasswordService(sl()));
sl.registerLazySingleton<BlockedUserService>(() => BlockedUserService(sl()));
sl.registerLazySingleton<CommentsService>(() => CommentsService(sl()));
sl.registerLazySingleton<MyRecipesService>(() => MyRecipesService(sl()));
sl.registerLazySingleton<ConsultantRatingService>(() => ConsultantRatingService(sl()));
sl.registerLazySingleton<NotificationSettingsService>(() => NotificationSettingsService(sl()));
sl.registerLazySingleton<ViewsService>(() => ViewsService(sl()));
sl.registerLazySingleton<ResetPasswordService>(
() => ResetPasswordService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<BlockedUserService>(
() => BlockedUserService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<CommentsService>(
() => CommentsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<MyRecipesService>(
() => MyRecipesService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ConsultantRatingService>(
() => ConsultantRatingService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<NotificationSettingsService>(
() => NotificationSettingsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<ViewsService>(
() => ViewsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<SbpService>(() => const SbpServiceImpl());
sl.registerLazySingleton<PersonalDietSuggestionService>(() => PersonalDietSuggestionService(sl()));
sl.registerLazySingleton<RegistrationServiceV2>(() => RegistrationServiceV2(sl()));
sl.registerLazySingleton<PersonalDietSuggestionService>(
() => PersonalDietSuggestionService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<RegistrationServiceV2>(
() => RegistrationServiceV2(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
// Content services
sl.registerLazySingleton<CreateRecipeService>(() => CreateRecipeService(sl()));
sl.registerLazySingleton<BlogPostService>(() => BlogPostService(sl()));
sl.registerLazySingleton<CreateDietService>(() => CreateDietService(sl()));
sl.registerLazySingleton<CreateRecipeService>(
() => CreateRecipeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<BlogPostService>(
() => BlogPostService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
sl.registerLazySingleton<CreateDietService>(
() => CreateDietService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
// Auth services
sl.registerLazySingleton<RegistrationService>(() => RegistrationService(sl()));
sl.registerLazySingleton<RegistrationService>(
() => RegistrationService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
);
}
}

View File

@@ -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<int>();
@override
Future<Response<T>> fetch<T>(RequestOptions requestOptions) async {
try {
return await super.fetch<T>(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<int> _statuses;
@override
Future<String> transformRequest(RequestOptions options) =>
_delegate.transformRequest(options);
@override
Future<dynamic> 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;
}
}
}

View File

@@ -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<bool>();
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<T>(
ApiResponseErrorReporter? reporter,
Response<dynamic> 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<dynamic>? 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<void> _send(
ApiResponseDecodeException error,
StackTrace stackTrace,
Map<String, Object?> 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)';
}

View File

@@ -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) {

View File

@@ -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<Dio>()
final response = await sl<Dio>()
.get('${sl<AppConfig>().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<ApiResponseErrorReporter>()
? sl<ApiResponseErrorReporter>()
: null;
final latestVersion = ApiResponseErrorReporter.decode(
responseErrors,
response,
'/api/app_versions',
() => Version.parse(versions['min_version']),
);
if (latestVersion > currentVersion) {
return null;
} else {

View File

@@ -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<void> viewContent({

View File

@@ -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<WebsocketInfoModel> getWebsocket();