onResponse method
Called when the response is about to be resolved.
Implementation
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
try {
final data = response.data;
// 如果不是自动解析,直接传递原始响应
if (!config.autoParse) {
return handler.next(response);
}
// 如果数据不是Map类型,直接传递
if (data is! Map<String, dynamic>) {
return handler.next(response);
}
// 提取状态码
final code = data[config.codeField];
// 如果code存在且不在成功列表中,认为请求失败
if (code != null && !config.successCodes.contains(code)) {
final message = data[config.messageField] ?? '请求失败';
// 使用reject传递异常
return handler.reject(
DioException(
requestOptions: response.requestOptions,
response: response,
type: DioExceptionType.badResponse,
error: message,
),
);
}
// 提取data字段(如果存在)
if (config.dataField.isNotEmpty && data.containsKey(config.dataField)) {
response.data = data[config.dataField];
}
return handler.next(response);
} catch (e) {
// 如果解析失败,返回原始响应
return handler.next(response);
}
}