execute<T> method
Future<SmartResponse<T> >
execute<T>(
- RequestContext ctx,
- Future<
Response< executor(T> >- RequestOptions options
- RequestOptions options
执行请求
ctx 请求上下文
executor 实际执行 Dio 请求的函数
Implementation
Future<SmartResponse<T>> execute<T>(
RequestContext ctx,
Future<Response<T>> Function(RequestOptions options) executor,
RequestOptions options,
) async {
// 按 priority 排序(数字越小越先执行)
final sorted = [...middlewares]
..sort((a, b) => a.priority.compareTo(b.priority));
ctx.startTime = DateTime.now();
try {
// 1. 执行 onStart
for (final m in sorted) {
await m.onStart(ctx);
}
// 2. 执行 onRequest(可修改 options)
for (final m in sorted) {
await m.onRequest(ctx, options);
}
// 3. 执行 Dio 请求
final response = await executor(options);
ctx.response = response;
// 4. 执行 onResponse
for (final m in sorted) {
await m.onResponse(ctx, response);
}
// 优先使用解析后的数据(来自 ResponseParserPlugin)
final parsedData = ctx.extras[kParsedDataKey];
return SmartResponse<T>(
data: parsedData ?? response.data,
raw: response,
);
} catch (e) {
// 5. 执行 onError - 使用新的 sealed SmartError
final error = SmartError.from(e);
ctx.error = error;
for (final m in sorted) {
await m.onError(ctx, error);
}
rethrow;
} finally {
ctx.endTime = DateTime.now();
// 6. 执行 onFinish(保证执行)
for (final m in sorted) {
try {
await m.onFinish(ctx);
} catch (_) {
// onFinish 中的异常不应影响主流程
}
}
}
}