在生产环境中妥善处理错误,以避免静默失败。当 getResult() 之类的调用失败时,SDK 会抛出一个 TracioError——它是 Error 的子类,带有一个机器可读的 code 字段。
用 try/catch 包裹 await tracio.getResult(),通过 isTracioError() 收窄抛出的值,然后根据 error.code 分支处理:
import { Tracio, isTracioError, isRetryableError } from "@tracio/sdk"
const tracio = Tracio.init({ publicKey: "5ca175fc..." })
try { const result = await tracio.getResult() console.log(result.visitorId, result.bot.detected)} catch (error) { if (isTracioError(error)) { if (isRetryableError(error)) { // Transient failure (network, timeout, blocked script, upstream) — // a fresh attempt may succeed. console.warn(`Retryable TRACIO error: ${error.code}`) } else { // Terminal failure (bad config, misuse, destroyed instance) — // fix the caller; retrying the same call will not help. console.error(`Terminal TRACIO error: ${error.code} — ${error.message}`) } } else { console.error("Unexpected error:", error) }}代理(agent)在后台异步加载。如果在你调用 getResult() 之前加载就已失败,该失败会通过 onError 回调传递。请在 init() 之后立即注册它:
const tracio = Tracio.init({ publicKey: "5ca175fc..." })
tracio.onError((error) => { // Same TracioError instance you would catch from getResult(). console.warn(`TRACIO failed to initialize: ${error.code}`)})
tracio.onReady((result) => { console.log("Visitor identified:", result.visitorId)})同一个错误依然可以通过 getResult() 观察到——两个通道你都可以使用。
每个 TracioError 都带有一个类型为 TracioErrorCode 的 code。retryable getter(以及 isRetryableError() 辅助函数)会报告重新尝试是否可能成功。
| Code | 含义 | 可重试 |
|---|---|---|
invalid_config | 传给 Tracio.init() 的配置无效 | 否 |
multiple_keys | 在同一页面上使用了多个 public key | 否 |
non_browser | 在浏览器之外 await 了 getResult()(例如在服务器端) | 否 |
load_failed | 代理脚本加载失败 | 是 |
blocked | 脚本被拦截(广告拦截器或 CSP) | 是 |
script_error | 已加载的脚本在初始化时抛出了错误 | 是 |
network | 访问 API 时发生网络/传输故障 | 是 |
timeout | 调用超出了配置的 timeoutMs 预算 | 是 |
server | 边缘/服务器返回了上游故障 | 是 |
destroyed | 实例在调用前已被销毁(通过 destroy()) | 否 |
终止性错误码(invalid_config、multiple_keys、non_browser、destroyed)表示配置、用法或生命周期问题——请修正调用方,或再次调用 Tracio.init()。可重试的错误码是暂时性的,重新尝试可能会成功。
对于可重试的错误,应针对一次全新的尝试进行带退避(backoff)的重试,而不是重新 await 同一个已被拒绝的 promise:
import { Tracio, isRetryableError } from "@tracio/sdk"
async function identifyWithRetry(maxAttempts = 3) { let attempt = 0 while (true) { const tracio = Tracio.init({ publicKey: "5ca175fc..." }) try { return await tracio.getResult() } catch (error) { attempt++ // Tear down before retrying: init() returns the cached instance for the // same key, and getResult() caches its (rejected) promise — so a genuine // fresh attempt requires destroy() first. tracio.destroy() if (!isRetryableError(error) || attempt >= maxAttempts) throw error await new Promise((r) => setTimeout(r, 2 ** attempt * 250)) } }}