You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用cockatiel包时NetworkError的导入路径疑问

解决cockatiel中NetworkError找不到导入来源的问题

cockatiel包本身不提供内置的NetworkError类型,这个错误类型通常来自你使用的HTTP客户端(如fetch、axios)或者需要你自定义实现,以下是几种可行的方案:

方案1:自定义NetworkError类

如果你需要明确匹配网络类错误,可以自己定义一个错误类,在请求捕获到网络相关错误时抛出它:

// 自定义NetworkError类
class NetworkError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NetworkError';
  }
}

// 导入cockatiel相关方法
import { retry, handleType, ExponentialBackoff} from 'cockatiel';

// 示例:在请求逻辑中抛出自定义NetworkError
async function fetchData() {
  try {
    const res = await fetch('your-api-url');
    if (!res.ok) throw new Error('Request failed');
    return res;
  } catch (err) {
    // 判断是否为网络相关错误(比如fetch的TypeError)
    if (err instanceof TypeError && err.message.includes('Failed to fetch')) {
      throw new NetworkError(err.message);
    }
    throw err;
  }
}

// 使用重试逻辑
const response = await retry(
  handleType(NetworkError),
  { maxAttempts: this.maxAttempt, backoff: new ExponentialBackoff({ maxDelay: this.maxDelayMs, initialDelay: this.initialDelayMs }) },
).execute(() => fetchData()) as HttpResponse;
return response;

方案2:匹配HTTP客户端自带的错误类型

如果你使用的是特定HTTP客户端,可以直接匹配它的错误类型:

  • 使用axios:axios抛出的AxiosError中,网络错误的code为ERR_NETWORK,可以通过handleIf来判断:
import axios from 'axios';
import { retry, handleIf, ExponentialBackoff} from 'cockatiel';

const response = await retry(
  handleIf(err => err instanceof axios.AxiosError && err.code === 'ERR_NETWORK'),
  { maxAttempts: this.maxAttempt, backoff: new ExponentialBackoff({ maxDelay: this.maxDelayMs, initialDelay: this.initialDelayMs }) },
).execute(() => axios.get('your-api-url')) as HttpResponse;
return response;
  • 使用Node.js内置fetch:fetch在网络失败时抛出TypeError,可以直接匹配这个类型:
import { retry, handleType, ExponentialBackoff} from 'cockatiel';

const response = await retry(
  handleType(TypeError),
  { maxAttempts: this.maxAttempt, backoff: new ExponentialBackoff({ maxDelay: this.maxDelayMs, initialDelay: this.initialDelayMs }) },
).execute(() => fetch('your-api-url').then(res => {
  if (!res.ok) throw new Error('Request failed');
  return res;
})) as HttpResponse;
return response;

方案3:直接匹配错误特征

如果不需要特定类,也可以通过错误的name或message来匹配:

import { retry, handleIf, ExponentialBackoff} from 'cockatiel';

const response = await retry(
  handleIf(err => err.name === 'NetworkError' || err.message.includes('network')),
  { maxAttempts: this.maxAttempt, backoff: new ExponentialBackoff({ maxDelay: this.maxDelayMs, initialDelay: this.initialDelayMs }) },
).execute(() => yourRequestFunction()) as HttpResponse;
return response;

内容的提问来源于stack exchange,提问作者Aniket Babhulkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:29:57