From 554b34123d061a10f3c3433e6d99e8293f3cb135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Klemen=20Tu=C5=A1ar?= Date: Sun, 9 Jun 2024 12:33:25 +0100 Subject: [PATCH] chore: better error handling in AliceChopperAdapter --- .../lib/alice_chopper_adapter.dart | 73 +++++++++++++------ 1 file changed, 51 insertions(+), 22 deletions(-) diff --git a/packages/alice_chopper/lib/alice_chopper_adapter.dart b/packages/alice_chopper/lib/alice_chopper_adapter.dart index ecd8336e..c12df6ab 100644 --- a/packages/alice_chopper/lib/alice_chopper_adapter.dart +++ b/packages/alice_chopper/lib/alice_chopper_adapter.dart @@ -3,6 +3,7 @@ import 'dart:convert' show utf8; import 'dart:io' show HttpHeaders; import 'package:alice/core/alice_adapter.dart'; +import 'package:alice/core/alice_utils.dart'; import 'package:alice/model/alice_http_call.dart'; import 'package:alice/model/alice_http_error.dart'; import 'package:alice/model/alice_http_request.dart'; @@ -57,33 +58,61 @@ class AliceChopperAdapter with AliceAdapter implements Interceptor { ..response = AliceHttpResponse(), ); - final Response response = await chain.proceed(chain.request); + try { + final Response response = await chain.proceed(chain.request); - aliceCore.addResponse( - AliceHttpResponse() - ..status = response.statusCode - ..body = response.body ?? '' - ..size = switch (response.body) { - dynamic body when body is String => utf8.encode(body).length, - dynamic body when body is List => body.length, - dynamic body when body == null => 0, - _ => utf8.encode(body.toString()).length, - } - ..time = DateTime.now() - ..headers = { - for (final MapEntry entry in response.headers.entries) - entry.key: entry.value - }, - requestId, - ); + aliceCore.addResponse( + AliceHttpResponse() + ..status = response.statusCode + ..body = response.body ?? '' + ..size = switch (response.body) { + dynamic body when body is String => utf8.encode(body).length, + dynamic body when body is List => body.length, + dynamic body when body == null => 0, + _ => utf8.encode(body.toString()).length, + } + ..time = DateTime.now() + ..headers = { + for (final MapEntry entry + in response.headers.entries) + entry.key: entry.value + }, + requestId, + ); - if (!response.isSuccessful || response.error != null) { + if (!response.isSuccessful || response.error != null) { + aliceCore.addError( + AliceHttpError()..error = response.error, + requestId, + ); + } + + return response; + } catch (error, stackTrace) { + /// Log error to Alice log + AliceUtils.log(error.toString()); + + /// Add empty response to Alice core + aliceCore.addResponse( + AliceHttpResponse() + ..status = 500 + ..body = error.toString() + ..size = utf8.encode(error.toString()).length + ..time = DateTime.now() + ..headers = {}, + requestId, + ); + + /// Add error to Alice core aliceCore.addError( - AliceHttpError()..error = response.error, + AliceHttpError() + ..error = error + ..stackTrace = stackTrace, requestId, ); - } - return response; + /// Rethrow error + rethrow; + } } }