我用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"
}
我关注this并为我的响应创建一个 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});
内置值(value)转换器:
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),
);
}
我如何处理错误响应?
最佳答案
事实证明,实现这一目标非常容易。虽然花了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
关于flutter - 将错误响应转换为特定模型 - 斩波器 flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61823533/