Skip to main content

Overview

The FAD SDK uses promise-based error handling. When a module encounters an error, the promise is rejected with a ResponseError object containing detailed information about the failure.
It is the developer’s full responsibility to handle errors appropriately and make decisions based on each error case.

ResponseError Structure

All errors thrown by the SDK follow a consistent structure:
ResponseError<T> {
  code: T;          // Error code specific to the module
  error: string;    // Human-readable error message
}

Properties

code
string | number
A unique identifier for the error type. The specific codes available depend on which module you’re using.
error
string
A descriptive error message explaining what went wrong. This message is intended for debugging and logging purposes.

Basic Error Handling

Always wrap SDK method calls in a try/catch block:
import FadSDK from '@fad-producto/fad-sdk';

const TOKEN = 'your-token';

async function initProcess() {
  const options = {
    environment: FadSDK.getFadEnvironments().UATHA
  };

  const FAD_SDK = new FadSDK(TOKEN, options);
  
  try {
    const response = await FAD_SDK.startRegula(CREDENTIALS, /* ... */);
    // Process successful response
    console.log('Success:', response);
    
  } catch (ex) {
    // Handle error
    console.error('Error code:', ex.code);
    console.error('Error message:', ex.error);
    
  } finally {
    // Always cleanup
    FAD_SDK.end();
  }
}

Module-Specific Error Handling

Each module has its own set of error codes. Access them via FadSDK.Errors.<ModuleName>.

Capture-id&R (Regula) Errors

try {
  const response = await FAD_SDK.startRegula(
    CREDENTIALS,
    FadSDK.Constants.Regula.CaptureType.CAMERA_SNAPSHOT,
    true,
    true
  );
  
  // Handle successful completion
  console.log(response);
  
} catch (ex) {
  if (ex.code === FadSDK.Errors.Regula.CAMERA_PERMISSION_DENIED) {
    alert('Camera permission denied. Please enable camera access.');
    
  } else if (ex.code === FadSDK.Errors.Regula.ID_PHOTO_NOT_FOUND) {
    alert('Face photo not found on ID. Please try again.');
    
  } else if (ex.code === FadSDK.Errors.Regula.OCR_NOT_FOUND) {
    alert('Could not extract OCR data. Please try again.');
    
  } else {
    alert('An error occurred: ' + ex.error);
  }
}
Common Scenarios:
  • CAMERA_PERMISSION_DENIED - User denied camera access
  • ID_PHOTO_NOT_FOUND - Face photo could not be extracted from the document
  • OCR_NOT_FOUND - OCR data could not be extracted from the document

Liveness-3D (Facetec) Errors

try {
  const response = await FAD_SDK.startFacetec(CREDENTIALS, CONFIGURATION);
  console.log('Liveness check passed:', response);
  
} catch (ex) {
  if (ex.code === FadSDK.Errors.Facetec.Session.CAMERA_NOT_RUNNING) {
    alert('Camera not supported. Please try another device.');
    
  } else if (ex.code === FadSDK.Errors.Facetec.Session.INITIALIZATION_NOT_COMPLETED) {
    alert('Facetec initialization failed. Please restart.');
    
  } else {
    console.error('Facetec error:', JSON.stringify(ex));
  }
}
Common Scenarios:
  • CAMERA_NOT_RUNNING - Camera is not accessible or not supported
  • INITIALIZATION_NOT_COMPLETED - Facetec SDK failed to initialize properly

Signature Module Errors

try {
  const response = await FAD_SDK.startSignature(CONFIGURATION);
  
  // Process signature data
  const faceVideoUrl = URL.createObjectURL(response.data.videoFace);
  const signatureVideoUrl = URL.createObjectURL(response.data.videoSignature);
  
} catch (ex) {
  if (ex.code === FadSDK.Errors.Signature.NOT_ACCEPT_CAMERA_PERMISSION) {
    alert('Camera not supported. Please try another device.');
  } else {
    alert('Signature error: ' + JSON.stringify(ex));
  }
}

Videoagreement Module Errors

try {
  const LEGEND = 'I agree to the terms and conditions...';
  const response = await FAD_SDK.startVideoagreement(LEGEND, CONFIGURATION);
  
  const videoUrl = URL.createObjectURL(response.data.video);
  
} catch (ex) {
  if (ex.code === FadSDK.Errors.Videoagreement.NOT_ACCEPT_CAMERA_PERMISSION) {
    alert('Camera not supported. Please try another device.');
  } else {
    alert('Video agreement error: ' + JSON.stringify(ex));
  }
}

Error Handling Patterns

Pattern 1: User-Friendly Messages

Provide clear guidance to users when errors occur:
const ERROR_MESSAGES = {
  [FadSDK.Errors.Regula.CAMERA_PERMISSION_DENIED]: 
    'We need camera access to verify your ID. Please enable it in your browser settings.',
  [FadSDK.Errors.Regula.ID_PHOTO_NOT_FOUND]: 
    'We couldn\'t detect a face on your ID. Please ensure good lighting and try again.',
  [FadSDK.Errors.Regula.OCR_NOT_FOUND]: 
    'We couldn\'t read your ID. Please ensure the text is clear and try again.'
};

try {
  const response = await FAD_SDK.startRegula(/* ... */);
} catch (ex) {
  const userMessage = ERROR_MESSAGES[ex.code] || 'An unexpected error occurred. Please try again.';
  alert(userMessage);
  console.error('Technical details:', ex);
}

Pattern 2: Retry Logic

Implement retry logic for recoverable errors:
async function captureIdWithRetry(maxRetries = 3) {
  let attempt = 0;
  
  while (attempt < maxRetries) {
    try {
      const response = await FAD_SDK.startRegula(/* ... */);
      return response; // Success!
      
    } catch (ex) {
      attempt++;
      
      // Only retry for specific errors
      const retryableErrors = [
        FadSDK.Errors.Regula.ID_PHOTO_NOT_FOUND,
        FadSDK.Errors.Regula.OCR_NOT_FOUND
      ];
      
      if (!retryableErrors.includes(ex.code) || attempt >= maxRetries) {
        throw ex; // Give up
      }
      
      console.log(`Retry attempt ${attempt}/${maxRetries}`);
    }
  }
}

Pattern 3: Error Logging and Analytics

Log errors for monitoring and debugging:
function logError(module, error, context) {
  const errorLog = {
    timestamp: new Date().toISOString(),
    module: module,
    code: error.code,
    message: error.error,
    context: context,
    userAgent: navigator.userAgent
  };
  
  // Send to your logging service
  console.error('SDK Error:', errorLog);
  
  // Optional: Send to analytics
  // analytics.track('sdk_error', errorLog);
}

try {
  const response = await FAD_SDK.startRegula(/* ... */);
} catch (ex) {
  logError('Regula', ex, { 
    captureType: 'CAMERA_SNAPSHOT',
    idData: true,
    idPhoto: true 
  });
  throw ex;
}

Pattern 4: Graceful Degradation

Handle errors gracefully and provide alternatives:
async function verifyIdentity() {
  try {
    // Try preferred method: Regula
    const response = await FAD_SDK.startRegula(/* ... */);
    return { method: 'regula', data: response };
    
  } catch (ex) {
    console.error('Regula failed:', ex);
    
    // Fallback to alternative method
    try {
      const response = await FAD_SDK.startCaptureId(/* ... */);
      return { method: 'captureId', data: response };
    } catch (fallbackEx) {
      console.error('Fallback also failed:', fallbackEx);
      throw fallbackEx;
    }
  }
}

Complete Error Handling Example

Here’s a comprehensive example combining multiple patterns:
import FadSDK from '@fad-producto/fad-sdk';

class FadSDKHandler {
  constructor(token, options) {
    this.sdk = new FadSDK(token, options);
  }

  async captureDocument(credentials, config, maxRetries = 3) {
    let attempt = 0;
    
    while (attempt < maxRetries) {
      try {
        const response = await this.sdk.startRegula(
          credentials,
          FadSDK.Constants.Regula.CaptureType.CAMERA_SNAPSHOT,
          true,
          true,
          config
        );
        
        // Check if user closed the module
        if (response.event === FadSDK.Constants.EventModule.MODULE_CLOSED) {
          return { cancelled: true };
        }
        
        // Success!
        return { success: true, data: response.data };
        
      } catch (ex) {
        attempt++;
        
        // Log error
        this.logError('startRegula', ex, attempt);
        
        // Handle specific errors
        if (ex.code === FadSDK.Errors.Regula.CAMERA_PERMISSION_DENIED) {
          return {
            success: false,
            error: 'CAMERA_PERMISSION_DENIED',
            message: 'Please enable camera access and try again.',
            recoverable: false
          };
        }
        
        // Retry for certain errors
        const retryableErrors = [
          FadSDK.Errors.Regula.ID_PHOTO_NOT_FOUND,
          FadSDK.Errors.Regula.OCR_NOT_FOUND
        ];
        
        if (!retryableErrors.includes(ex.code) || attempt >= maxRetries) {
          return {
            success: false,
            error: ex.code,
            message: ex.error,
            recoverable: retryableErrors.includes(ex.code)
          };
        }
        
        // Wait before retry
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
  }
  
  logError(method, error, attempt) {
    console.error({
      timestamp: new Date().toISOString(),
      method,
      attempt,
      code: error.code,
      message: error.error
    });
  }
  
  cleanup() {
    this.sdk.end();
  }
}

// Usage
async function main() {
  const handler = new FadSDKHandler(TOKEN, {
    environment: FadSDK.getFadEnvironments().UATHA
  });
  
  try {
    const result = await handler.captureDocument(CREDENTIALS, CONFIGURATION);
    
    if (result.cancelled) {
      console.log('User cancelled the process');
    } else if (result.success) {
      console.log('Document captured successfully:', result.data);
    } else {
      console.error('Failed to capture document:', result.message);
      if (result.recoverable) {
        // Offer user the option to try again
      }
    }
  } finally {
    handler.cleanup();
  }
}

Best Practices

Always call end() in a finally block to ensure resources are released:
try {
  const response = await FAD_SDK.startModule(/* ... */);
} catch (error) {
  // Handle error
} finally {
  FAD_SDK.end(); // Always cleanup
}
Error codes and their meanings may vary by module. Always consult the specific module documentation for the complete list of error codes.

Next Steps

Module Overview

Learn about available modules and their specific error codes

Examples

View complete examples with error handling

Build docs developers (and LLMs) love