n8n node의 오류 처리
적절한 오류 처리는 문제가 발생했을 때 사용자에게 명확한 피드백을 제공하는 강력한 n8n node를 만드는 데 중요합니다. 외부 API 호출 및 HTTP 요청을 처리할 때 NodeApiError를 사용합니다. 다음 패턴을 사용하여 새 NodeApiError 인스턴스를 초기화합니다:
적절한 오류 처리는 문제가 발생했을 때 사용자에게 명확한 피드백을 제공하는 강력한 n8n node를 만드는 데 중요합니다. n8n은 node 구현에서 다양한 유형의 실패를 처리하기 위해 두 가지 특수 오류 클래스를 제공합니다:
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 (let i = 0; i < items.length; i++) {
try {
// 항목 처리
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,
});
}
}
