n8n 노드의 오류 처리
n8n v2.42요약
적절한 오류 처리는 문제가 발생했을 때 사용자에게 명확한 피드백을 제공하는 견고한 n8n 노드를 만드는 데 매우 중요합니다. 이 섹션의 상세 내용은 n8n 공식 문서를 참조하세요. 외부 API 호출과 HTTP 요청을 다룰 때는 NodeApiError를 사용합니다.
적절한 오류 처리는 문제가 발생했을 때 사용자에게 명확한 피드백을 제공하는 견고한 n8n 노드를 만드는 데 매우 중요합니다. n8n은 노드 구현에서 발생하는 다양한 유형의 실패를 처리하기 위해 두 가지 전용 오류 클래스를 제공합니다.
NodeApiError: API 관련 오류 및 외부 서비스 실패에 사용NodeOperationError: 운영 오류, 유효성 검사 실패, 구성 문제에 사용
이 섹션의 상세 내용은 n8n 공식 문서를 참조하세요.
NodeApiError#
외부 API 호출과 HTTP 요청을 다룰 때는 NodeApiError를 사용합니다. 이 오류 클래스는 API 응답 오류를 처리하기 위해 특별히 설계되었으며, 다음과 같은 API 관련 실패를 파싱하고 표시하기 위한 향상된 기능을 제공합니다.
- HTTP 요청 실패
- 외부 API 오류
- 인증/인가 실패
- 요청 제한(rate limiting) 오류
- 서비스 이용 불가 오류
다음 패턴을 사용하여 새 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 |
노드 자체의 버그입니다. 자격 증명이나 구성 어느 쪽의 문제도 아닙니다. |
대기 힌트#
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 오류 분류하기#
응답으로 입증되는 원인만 선언하세요. 오류를 확실하게 분류할 수 없으면 그대로 throw 하세요. 선언이 없는 오류도 유효합니다.
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);
}