Files
umbrix/lib/domain/failures.dart

69 lines
1.9 KiB
Dart
Raw Normal View History

2023-09-06 12:56:30 +03:30
import 'package:dio/dio.dart';
import 'package:hiddify/core/prefs/prefs.dart';
2023-07-06 17:18:41 +03:30
mixin Failure {
2023-08-26 17:01:51 +03:30
({String type, String? message}) present(TranslationsEn t);
2023-07-06 17:18:41 +03:30
}
2023-10-03 21:12:14 +03:30
mixin UnexpectedFailure {
Object? get error;
StackTrace? get stackTrace;
}
2023-09-22 14:17:42 +03:30
/// failures ignored by analytics service etc.
mixin ExpectedException {}
2023-07-06 17:18:41 +03:30
extension ErrorPresenter on TranslationsEn {
2023-09-06 12:56:30 +03:30
String? _errorToMessage(Object error) {
switch (error) {
case Failure():
final err = error.present(this);
return err.type + (err.message == null ? "" : ": ${err.message}");
case DioException():
return error.present(this);
2023-09-06 12:56:30 +03:30
default:
return null;
2023-08-26 17:01:51 +03:30
}
2023-07-06 17:18:41 +03:30
}
2023-08-26 17:01:51 +03:30
2023-09-06 12:56:30 +03:30
String printError(Object error) =>
_errorToMessage(error) ?? failure.unexpected;
String? mayPrintError(Object? error) =>
error != null ? _errorToMessage(error) : null;
({String type, String? message}) presentError(
Object error, {
String? action,
}) {
final ({String type, String? message}) presentable;
if (error case Failure()) {
presentable = error.present(this);
} else {
presentable = (type: failure.unexpected, message: null);
}
return (
type: action == null ? presentable.type : "$action: ${presentable.type}",
message: presentable.message,
);
}
}
extension DioExceptionPresenter on DioException {
String presentType(TranslationsEn t) => switch (type) {
DioExceptionType.connectionTimeout ||
DioExceptionType.sendTimeout ||
DioExceptionType.receiveTimeout =>
t.failure.connection.timeout,
DioExceptionType.badCertificate => t.failure.connection.badCertificate,
DioExceptionType.badResponse => t.failure.connection.badResponse,
DioExceptionType.connectionError =>
t.failure.connection.connectionError,
_ => t.failure.unexpected,
};
String present(TranslationsEn t) {
return presentType(t) + (message == null ? "" : "\n$message");
2023-08-26 17:01:51 +03:30
}
2023-07-06 17:18:41 +03:30
}