Skip to content

n8n 节点中的错误处理#

¥Error handling in n8n nodes

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

¥Proper error handling is crucial for creating robust n8n nodes that provide clear feedback to users when things go wrong. n8n provides two specialized error classes to handle different types of failures in node implementations:

  • NodeApiError:对于 API 相关错误和外部服务故障

¥NodeApiError: For API-related errors and external service failures

¥NodeOperationError: For operational errors, validation failures, and configuration issues

NodeApiError#

处理外部 API 调用和 HTTP 请求时,请使用 NodeApiError。此错误类专门用于处理 API 响应错误,并提供增强功能来解析和呈现与 API 相关的故障,例如:

¥Use NodeApiError when dealing with external API calls and HTTP requests. This error class is specifically designed to handle API response errors and provides enhanced features for parsing and presenting API-related failures such as:

  • HTTP 请求失败

¥HTTP request failures

  • 外部 API 错误

¥external API errors

  • 身份验证/授权失败

¥authentication/authorization failures

  • 速率限制错误

¥rate limiting errors

  • 服务不可用错误

¥service unavailable errors

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

¥Initialize new NodeApiError instances using the following pattern:

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

常见使用模式#

¥Common usage patterns

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

¥For basic API request failures, catch the error and wrap it in 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 状态码:

¥Handle specific HTTP status codes with custom messages:

 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
34
35
36
37
38
39
40
41
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 用于:

¥Use NodeOperationError for:

  • 操作错误

¥operational errors

  • 验证失败

¥validation failures

  • 与外部 API 调用无关的配置问题

¥configuration issues that aren't related to external API calls

  • 输入验证错误

¥input validation errors

  • 缺少必需参数

¥missing required parameters

  • 数据转换错误

¥data transformation errors

  • 工作流逻辑错误

¥workflow logic errors

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

¥Initialize new NodeOperationError instances using the following pattern:

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

常见使用模式#

¥Common usage patterns

使用 NodeOperationError 验证用户输入:

¥Use NodeOperationError for validating user inputs:

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

处理多个项目时,请包含项目索引以便更好地了解错误上下文:

¥When processing multiple items, include the item index for better error context:

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