n8n 节点中的错误处理
正确的错误处理对于创建健壮的 n8n 节点至关重要,它能在出现问题时为用户提供清晰的反馈。n8n 提供了两个专门的错误类来处理节点实现中的不同类型的故障:
NodeApiError: 用于 API 相关错误和外部服务故障NodeOperationError: 用于操作错误、验证失败和配置问题
NodeApiError
在处理外部 API 调用和 HTTP 请求时使用 NodeApiError。这个错误类专门设计用于处理 API 响应错误,并为解析和呈现 API 相关故障提供增强功能,例如:
- HTTP 请求失败
- 外部 API 错误
- 身份验证/授权失败
- 速率限制错误
- 服务不可用错误
使用以下模式初始化新的 NodeApiError 实例:
new NodeApiError(node: INode, errorResponse: JsonObject, options?: NodeApiErrorOptions)
常见使用模式
对于基本的 API 请求失败,捕获错误并将其包装在 NodeApiError 中:
try {
const response = await this.helpers.httpRequestWithAuthentication.call(
this,
credentialType,
options
);
return response;
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
}
使用自定义消息处理特定的 HTTP 状态码:
try {
const response = await this.helpers.httpRequestWithAuthentication.call(
this,
credentialType,
options
);
return response;
} catch (error) {
if (error.httpCode === "404") {
const resource = this.getNodeParameter("resource", 0);
const errorOptions = {
message: `${
resource.charAt(0).toUpperCase() + resource.slice(1)
} not found`,
description:
"The requested resource could not be found. Please check your input parameters.",
};
throw new NodeApiError(
this.getNode(),
error as JsonObject,
errorOptions
);
}
if (error.httpCode === "401") {
throw new NodeApiError(this.getNode(), error as JsonObject, {
message: "Authentication failed",
description: "Please check your credentials and try again.",
});
}
throw new NodeApiError(this.getNode(), error as JsonObject);
}
NodeOperationError
使用 NodeOperationError 处理:
- 操作错误
- 验证失败
- 与外部 API 调用无关的配置问题
- 输入验证错误
- 缺少必需参数
- 数据转换错误
- 工作流逻辑错误
使用以下模式初始化新的 NodeOperationError 实例:
new NodeOperationError(node: INode, error: Error | string | JsonObject, options?: NodeOperationErrorOptions)
常见使用模式
使用 NodeOperationError 验证用户输入:
const email = this.getNodeParameter("email", itemIndex);
if (email.indexOf("@") === -1) {
const description = `The email address '${email}' in the 'email' field isn't valid`;
throw new NodeOperationError(this.getNode(), "Invalid email address", {
description,
itemIndex, // for multiple items, this will link the error to the specific item
});
}
处理多个数据项时,包含数据项索引以获得更好的错误上下文:
for (let i = 0; i < items.length; i++) {
try {
// Process item
const result = await processItem(items[i]);
returnData.push(result);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({
json: { error: error.message },
pairedItem: { item: i },
});
continue;
}
throw new NodeOperationError(this.getNode(), error as Error, {
description: error.description,
itemIndex: i,
});
}
}
声明操作失败的原因
提示
功能可用性
失败声明从 n8n 3.37 开始提供。
NodeApiError 和 NodeOperationError 都接受 failure 选项,用来说明操作失败的原因。当节点能从响应中判断问题所在时(例如配额已用尽或凭据不再有效),请使用此选项。声明会以普通数据形式写入错误的 failure 属性。节点只声明原因,不决定如何处理;由 n8n 负责根据声明执行相应行为,例如轮询触发器在一次轮询失败后如何退避。
构造错误时传入此声明:
throw new NodeApiError(this.getNode(), error as JsonObject, {
failure: { cause: 'rate-limited' },
});
失败原因
cause 字段接受六个值。前三种故障会自行恢复,后三种则需要有人采取操作后,操作才能成功。
cause |
含义 |
|---|---|
rate-limited |
服务正在限制请求。 |
quota-exhausted |
使用配额已耗尽,在配额重置前操作都会失败。 |
temporarily-unavailable |
服务当前不可用或性能下降。 |
credential-invalid |
凭据不再有效,用户必须重新连接。 |
configuration-invalid |
节点指向的对象不再存在或不再被允许。 |
node-defect |
节点本身存在 bug;问题不在凭据或配置。 |
等待提示
对于 rate-limited、quota-exhausted 和 temporarily-unavailable,可以选择添加关于操作何时可能恢复的提示。其他原因不接受此类提示,因为等待无法解决问题。
| 字段 | 含义 |
|---|---|
retryAfterMs |
服务要求的最短等待时间,以毫秒为单位。 |
resetsAtEpochMs |
服务表示操作可恢复的时间,以 Unix epoch 毫秒表示。 |
例如,已知重置时间的配额可声明恢复时间:
throw new NodeApiError(this.getNode(), error as JsonObject, {
failure: { cause: 'quota-exhausted', resetsAtEpochMs: nextQuotaReset() },
});
对 API 错误分类
只有响应能够证明原因时,才声明该原因。如果无法确信错误类别,请原样抛出;没有声明的错误仍然有效。
try {
return await this.helpers.httpRequestWithAuthentication.call(
this,
credentialType,
options
);
} catch (error) {
if (error.httpCode === "401") {
throw new NodeApiError(this.getNode(), error as JsonObject, {
failure: { cause: "credential-invalid" },
});
}
if (error.httpCode === "429") {
throw new NodeApiError(this.getNode(), error as JsonObject, {
failure: { cause: "rate-limited" },
});
}
throw new NodeApiError(this.getNode(), error as JsonObject);
}