onFailure method

Future<Response<T>> onFailure(
  1. void callback(
    1. int? httpStatusCode,
    2. int? errorCode,
    3. String message
    )
)

等待响应完成后,失败时执行回调 支持链式调用,无需中间变量

示例:

await http.send(...).onFailure((httpStatusCode, errorCode, message) {
  print('HTTP 状态码: $httpStatusCode, 业务错误码: $errorCode, 错误消息: $message');
  if (httpStatusCode == 401) {
    // 处理 HTTP 401 未授权
  } else if (errorCode == 1001) {
    // 处理业务错误码 1001
  }
});

Implementation

Future<Response<T>> onFailure(
    void Function(int? httpStatusCode, int? errorCode, String message)
        callback) async {
  final response = await this;
  final result = response.onFailure(callback);
  // 注意:不再在这里关闭 loading
  // - 如果使用了 http.isLoading.send(),这是链式调用,loading 应该由链式调用的最后一步关闭
  // - 如果使用了 http.send(isLoading: true),finally 块会处理关闭 loading
  // - 如果后续有链式调用,loading 应该由链式调用的最后一步关闭
  return result;
}