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: For API-related errors and external service failures
NodeOperationError: For operational errors, validation failures, and configuration issues
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 request failures
external API errors
authentication/authorization failures
rate limiting errors
service unavailable errors
Initialize new NodeApiError instances using the following pattern:
try{constresponse=awaitthis.helpers.requestWithAuthentication.call(this,credentialType,options);returnresponse;}catch(error){if(error.httpCode==="404"){constresource=this.getNodeParameter("resource",0)asstring;consterrorOptions={message:`${resource.charAt(0).toUpperCase()+resource.slice(1)} not found`,description:"The requested resource could not be found. Please check your input parameters.",};thrownewNodeApiError(this.getNode(),errorasJsonObject,errorOptions);}if(error.httpCode==="401"){thrownewNodeApiError(this.getNode(),errorasJsonObject,{message:"Authentication failed",description:"Please check your credentials and try again.",});}thrownewNodeApiError(this.getNode(),errorasJsonObject);}
Use NodeOperationError for validating user inputs:
123456789
constemail=this.getNodeParameter("email",itemIndex)asstring;if(email.indexOf("@")===-1){constdescription=`The email address '${email}' in the 'email' field isn't valid`;thrownewNodeOperationError(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 91011121314151617181920
for(leti=0;i<items.length;i++){try{// Process itemconstresult=awaitprocessItem(items[i]);returnData.push(result);}catch(error){if(this.continueOnFail()){returnData.push({json:{error:error.message},pairedItem:{item:i},});continue;}thrownewNodeOperationError(this.getNode(),errorasError,{description:error.description,itemIndex:i,});}}