Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ Introduce DioExceptionLogBuilder
Browse files Browse the repository at this point in the history
AlexV525 committed Sep 18, 2024
1 parent 551c93f commit a8a8d38
Showing 2 changed files with 27 additions and 6 deletions.
29 changes: 25 additions & 4 deletions dio/lib/src/dio_exception.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'options.dart';
import 'response.dart';
import 'utils.dart' show warningLog;

/// Deprecated in favor of [DioExceptionType] and will be removed in future major versions.
@Deprecated('Use DioExceptionType instead. This will be removed in 6.0.0')
@@ -205,6 +206,9 @@ class DioException implements Exception {
/// The error message that throws a [DioException].
final String? message;

/// Users can customize the logging content when a [DioException] was thrown.
static DioExceptionLogBuilder logBuilder = defaultDioExceptionLogBuilder;

/// Generate a new [DioException] by combining given values and original values.
DioException copyWith({
RequestOptions? requestOptions,
@@ -226,11 +230,12 @@ class DioException implements Exception {

@override
String toString() {
String msg = 'DioException [${type.toPrettyDescription()}]: $message';
if (error != null) {
msg += '\nError: $error';
try {
return logBuilder(this);
} catch (e, s) {
warningLog(e, s);
return defaultDioExceptionLogBuilder(this);
}
return msg;
}

/// Because of [ValidateStatus] we need to consider all status codes when
@@ -278,3 +283,19 @@ class DioException implements Exception {
return buffer.toString();
}
}

/// The log builder's signature.
typedef DioExceptionLogBuilder = String Function(DioException e);

/// The default implementation of logging the [DioException] as text content.
String defaultDioExceptionLogBuilder(DioException e) {
final buffer = StringBuffer(
'DioException [${e.type.toPrettyDescription()}]: '
'${e.message}',
);
if (e.error != null) {
buffer.writeln();
buffer.write('Error: ${e.error}');
}
return buffer.toString();
}
4 changes: 2 additions & 2 deletions dio/lib/src/utils.dart
Original file line number Diff line number Diff line change
@@ -154,10 +154,10 @@ Map<String, V> caseInsensitiveKeyMap<V>([Map<String, V>? value]) {
}

// TODO(Alex): Provide a configurable property on the Dio class once https://github.com/cfug/dio/discussions/1982 has made some progress.
void warningLog(String message, StackTrace stackTrace) {
void warningLog(Object message, StackTrace stackTrace) {
if (!kReleaseMode) {
dev.log(
message,
message.toString(),
level: 900,
name: '🔔 Dio',
stackTrace: stackTrace,

0 comments on commit a8a8d38

Please sign in to comment.