1

我使用chopper客户端发出 http 请求

我写了一个 api,它必须有响应类型:使用这种格式成功:

{
    "id": 1,
    "title": "Most Popular phone in the world !",
    "image": "/uploads/poll_images/D6voYQriTCSZpMIe.jpg",
    "submits": 2,
    "views": 52,
    "description": "There are many phone on the world, if you are buyer which one will you buy ?",
    "date": {
        "date": "2020.4.13",
        "time": "12:02"
    },
    "comments": 0,
    "options": [
        {
            "id": 1,
            "position": 1,
            "title": "iPhone 11 pro Max",
            "votes": 1
        },
        {
            "id": 2,
            "position": 2,
            "title": "Samsung S20+ Ultra",
            "votes": 1
        }
    ],
    "selected": 2
}

状态码为 400 的错误响应,格式如下:

{
    "msg": "Your login session expired! please login again"
}

我遵循这个并为我的响应创建一个 buildValue 转换器。

一切都很好,响应成功转换为数据模型,但我不知道如何处理我的错误响应!

这是我的创建方法:

static ApiService create() {
    if (instance == null) {
      instance = ChopperClient(
        baseUrl: Commons.baseURL,
        services: [_$ApiService()],
        interceptors: [HttpLoggingInterceptor()],
        converter: BuiltValueConverter(),
        errorConverter: BuiltValueConverter(),
      );
    }
    return _$ApiService(instance);
  }

请求方法:

@Get(path: 'poll/getSingle/{id}')
  Future<Response<PollSingle>> getPollSingle({@Path('id') int pollId , @Query('client_id') int clientId});

内置值转换器:

class BuiltValueConverter extends JsonConverter {
  final jsonSerializers =
      (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

  T _deserializer<T>(dynamic value) => jsonSerializers.deserializeWith(
        jsonSerializers.serializerForType(T),
        value,
      );

  @override
  Response<ResultType> convertResponse<ResultType, Item>(Response response) {
    final jsonResponse = super.convertResponse(response);
    final body = _decode<Item>(jsonResponse.body);

    return jsonResponse.copyWith<ResultType>(body: body);
  }

  dynamic _decode<T>(entity) {
    print(entity);
    if (entity is T) return entity;

    try {
      if (entity is List) return _deserializeListOf<T>(entity);
      return _deserializer<T>(entity);
    } catch (e) {
      print(e);
      return null;
    }
  }

  BuiltList<T> _deserializeListOf<T>(Iterable value) => BuiltList(
        value.map((value) => _deserializer<T>(value)).toList(growable: true),
      );
}

我该如何处理错误响应?

4

1 回答 1

1

事实证明,实现这一点真的很容易。花了2天时间试图弄清楚。因此,在您PollSingle将额外的服务器响应消息添加为

@nullable
String get msg;

然后在您处理逻辑的任何地方,检查服务器请求是否成功。假设您的响应存储在response变量中,

var response = ApiService.create().getPollSingle('id', 'client_id');
if (! response.isSuccessful && response.statusCode == 400) {
    var errors = response.error as PollSingle;
    print(errors);
}

你应该得到

PollSingle {
   msg=Your login session expired! please login again,
}

所以你可以轻松做到errors.msg

于 2020-05-27T00:38:51.327 回答