瀏覽代碼

1、jsonrpc新增一个http请求错误的返回

guanxinyi 1 年之前
父節點
當前提交
737cc9e7f6
共有 2 個文件被更改,包括 32 次插入5 次删除
  1. 17 5
      lib/client_base.dart
  2. 15 0
      lib/interceptor.dart

+ 17 - 5
lib/client_base.dart

@@ -66,14 +66,20 @@ class JsonRpcClientBase {
   }
 
   Future<dynamic> _transmit(JsonRpcRequest request) async {
-    final req = await jsonRpcInterceptHost.onRequestTransmit(request);
+    var result;
+    try {
+      final req = await jsonRpcInterceptHost.onRequestTransmit(request);
 
-    String package = jsonEncode(req.toJson());
+      String package = jsonEncode(req.toJson());
 
-    var response = await _postRequest(package);
-    if (response == null) throw JsonRpcException(message: "Response Empty");
+      var response = await _postRequest(package);
+      if (response == null) throw JsonRpcException(message: "Response Empty");
 
-    var result = await _handleDecoded(response);
+      result = await _handleDecoded(response);
+    } catch (e) {
+      await _handleHttpRequestError(JsonRpcNetworkException(e.toString()));
+      // throw JsonRpcException(message: "Http error", data: e);
+    }
     return result;
   }
 
@@ -104,6 +110,12 @@ class JsonRpcClientBase {
     }
   }
 
+  Future<dynamic> _handleHttpRequestError(JsonRpcNetworkException error) async {
+    final res = await jsonRpcInterceptHost.onHttpRequestError(error);
+
+    throw res;
+  }
+
   Future<dynamic> _handleDecoded(Map<String, dynamic> response) async {
     final res = await jsonRpcInterceptHost.onResponse(response);
     if (res.containsKey('error')) {

+ 15 - 0
lib/interceptor.dart

@@ -18,6 +18,11 @@ abstract class JsonRpcInterceptor {
   Future<JsonRpcServerError> onResponseError(JsonRpcServerError error) async {
     return error;
   }
+
+  Future<JsonRpcNetworkException> onHttpRequestError(
+      JsonRpcNetworkException error) async {
+    return error;
+  }
 }
 
 class _JsonRpcInterceptHost implements JsonRpcInterceptor {
@@ -54,6 +59,16 @@ class _JsonRpcInterceptHost implements JsonRpcInterceptor {
     return pipeVal;
   }
 
+  @override
+  Future<JsonRpcNetworkException> onHttpRequestError(
+      JsonRpcNetworkException error) async {
+    var pipeVal = error;
+    for (var interceptor in _interceptors) {
+      pipeVal = await interceptor.onHttpRequestError(pipeVal);
+    }
+    return pipeVal;
+  }
+
   @override
   Future onResponseResult(result) async {
     var pipeVal = result;