我使用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),
);
}
我该如何处理错误响应?