跳转至

n8n节点中的错误处理#

适当的错误处理对于创建稳健的n8n节点至关重要,这些节点可以在出现问题时向用户提供清晰的反馈。n8n提供了两个专门的错误类来处理节点实现中不同类型的失败:

NodeApiError#

在处理外部API调用和HTTP请求时使用NodeApiError。这个错误类专门设计用于处理API响应错误,并为解析和展示API相关失败提供增强功能,如:

  • HTTP请求失败
  • 外部API错误
  • 身份验证/授权失败
  • 限率错误
  • 服务不可用错误

使用以下模式初始化新的NodeApiError实例:

1
new NodeApiError(node: INode, errorResponse: JsonObject, options?: NodeApiErrorOptions)

常见使用模式#

对于基本的API请求失败,捕获错误并将其包装在NodeApiError中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try {
	const response = await this.helpers.requestWithAuthentication.call(
		this,
		credentialType,
		options
	);
	return response;
} catch (error) {
	throw new NodeApiError(this.getNode(), error as JsonObject);
}

使用自定义消息处理特定的HTTP状态码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
try {
	const response = await this.helpers.requestWithAuthentication.call(
		this,
		credentialType,
		options
	);
	return response;
} catch (error) {
	if (error.httpCode === "404") {
		const resource = this.getNodeParameter("resource", 0) as string;
		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实例:

1
new NodeOperationError(node: INode, error: Error | string | JsonObject, options?: NodeOperationErrorOptions)

常见使用模式#

使用NodeOperationError验证用户输入:

1
2
3
4
5
6
7
8
9
const email = this.getNodeParameter("email", itemIndex) as string;

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
	});
}

在处理多个项目时,包含项目索引以获得更好的错误上下文:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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实战笔记公众号
n8n实战笔记
📚 教程 💡 案例 🔧 技巧
添加微信
添加作者微信
1对1 专业指导
⚡ 快答 🎯 定制 🚀 支持