Created
October 2, 2024 14:05
-
-
Save shinayser/98af722f862c23b829e0c3324a9b59b0 to your computer and use it in GitHub Desktop.
Demo showing how dio can freeze/crash the app if an error occurs inside the interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:dio/dio.dart'; | |
Future<void> main() async { | |
final dio = Dio(); | |
//Using the same dio instance: crash | |
dio.interceptors.add(InterceptorWithError(dio)); | |
//Using different instance: works | |
//dio.interceptors.add(InterceptorWithError(Dio())); | |
try { | |
final response = await Future.wait([ | |
dio.get('https://1'), | |
dio.get('https://2'), | |
]); | |
print('Response: ${response.length}'); | |
} catch (e) { | |
print('Unreachable code: $e'); | |
} | |
print('Code end'); | |
} | |
class InterceptorWithError extends QueuedInterceptorsWrapper { | |
final Dio dio; | |
InterceptorWithError(this.dio); | |
@override | |
Future<void> onRequest( | |
RequestOptions options, | |
RequestInterceptorHandler handler, | |
) async { | |
print('Request: ${options.path}'); | |
return handler.next(options); | |
} | |
@override | |
Future<void> onError( | |
DioException err, | |
ErrorInterceptorHandler handler, | |
) async { | |
var requestOptions = err.requestOptions; | |
try { | |
handler.resolve(await dio.fetch(requestOptions.copyWith( | |
path: (err.requestOptions.path.contains('1')) | |
? 'https://www.xoogle.com' | |
: 'https://www.google.com', | |
))); | |
} catch (e) { | |
print('Quebrou o fetch ---> $e'); | |
handler.next(err); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment