Skip to main content
Version: Next

Error handling

Overview

In order to handle different types of errors, you can use instanceof with our exported class RnExecutorchError and its code property. This allows you to check what exactly went wrong and act accordingly.

This example uses the LLMModule, and then tries to change its generationConfig. As the topp param has to be a value between 0 and 1 (inclusive), the .configure() method will throw an error with a code InvalidConfig.

import {
LLMModule,
LLAMA3_2_1B_QLORA,
RnExecutorchError,
RnExecutorchErrorCode,
} from 'react-native-executorch';

const llm = new LLMModule({
tokenCallback: (token) => console.log(token),
messageHistoryCallback: (messages) => console.log(messages),
});

await llm.load(LLAMA3_2_1B_QLORA, (progress) => console.log(progress));

// Try to set an invalid configuration
try {
await llm.configure({ topp: 1.5 }); // This will throw InvalidConfig error
} catch (err) {
if (
err instanceof RnExecutorchError &&
err.code === RnExecutorchErrorCode.InvalidConfig
) {
console.error('Invalid configuration:', err.message);
// Handle the invalid config - set default values
await llm.configure({ topp: 0.9 });
} else {
throw err;
}
}

// Running the model
try {
await llm.sendMessage('Hello, World!');
} catch (err) {
if (err instanceof RnExecutorchError) {
if (err.code === RnExecutorchErrorCode.ModuleNotLoaded) {
console.error('Model not loaded:', err.message);
// Load the model first
} else if (err.code === RnExecutorchErrorCode.ModelGenerating) {
console.error('Model is already generating:', err.message);
// Wait for current generation to complete
} else {
console.error('Generation error:', err.message);
throw err;
}
} else {
throw err;
}
}

// Interrupting the model (to actually interrupt the generation it has to be called when sendMessage or generate is running)
llm.interrupt();

// Deleting the model from memory
llm.delete();

Reference

All errors in React Native ExecuTorch inherit from RnExecutorchError and include a code property from the RnExecutorchErrorCode enum. Below is a comprehensive list of all possible errors, organized by category.

Module State Errors

These errors occur when trying to perform operations on a model in an invalid state.

Error CodeDescriptionWhen It OccursHow to Handle
ModuleNotLoadedModel is not loaded into memoryCalling forward(), generate(), or other inference methods before calling load()Load the model first with load()
ModelGeneratingModel is already processing a requestCalling generate() or forward() while another inference is runningWait for current generation to complete, or use interrupt() to cancel it

Configuration Errors

These errors occur when invalid configuration or input is provided.

Error CodeDescriptionWhen It OccursHow to Handle
InvalidConfigConfiguration parameters are invalidSetting parameters outside valid ranges (e.g., topp outside [0, 1])Check parameter constraints and provide valid values
InvalidUserInputInput provided to API is invalidPassing empty arrays, null values, or malformed data to methodsValidate input before calling methods
InvalidModelSourceModel source type is invalidProviding wrong type for model source (e.g., object when string expected)Ensure model source matches expected type
LanguageNotSupportedLanguage not supported by modelPassing unsupported language to multilingual OCR or Speech-to-Text modelsUse a supported language or different model
WrongDimensionsInput tensor dimensions don't matchProviding input with incorrect shape for the modelCheck model's expected input dimensions
UnexpectedNumInputsWrong number of inputs providedPassing more or fewer inputs than model expectsMatch the number of inputs to model metadata

File Operations Errors

These errors occur during file read/write operations.

Error CodeDescriptionWhen It OccursHow to Handle
FileReadFailedFile read operation failedInvalid image URL, unsupported format, or file doesn't existVerify file path and format are correct
FileWriteFailedFile write operation failedSaving result image or output file failsCheck storage permissions and available space

Download & Resource Fetcher Errors

These errors occur during model download and resource management.

Error CodeDescriptionWhen It OccursHow to Handle
DownloadInterruptedDownload was interruptedNot all files were downloaded successfullyRetry the download
ResourceFetcherDownloadFailedResource download failedNetwork error, invalid URL, or server errorCheck network connection and URL validity, retry with exponential backoff
ResourceFetcherDownloadInProgressDownload already in progressCalling fetch() for same resource while downloadingWait for current download to complete
ResourceFetcherAlreadyPausedDownload already pausedCalling pauseFetching() on already paused downloadCheck download state before pausing
ResourceFetcherAlreadyOngoingDownload already ongoingCalling resumeFetching() on active downloadNo action needed, download is already running
ResourceFetcherNotActiveNo active download foundCalling pause/resume/cancel on non-existent downloadVerify download was started before trying to control it
ResourceFetcherMissingUriRequired URI information missingInternal state error during download operationsRestart the download from beginning

Speech-to-Text Streaming Errors

These errors are specific to streaming transcription operations.

Error CodeDescriptionWhen It OccursHow to Handle
MultilingualConfigurationMultilingual configuration mismatchSetting language on non-multilingual model, or not setting language on multilingual modelCheck if model is multilingual and provide language accordingly
MissingDataChunkAudio data chunk missingStreaming transcription without providing audio dataEnsure audio data is provided to streaming methods
StreamingNotStartedStream not startedCalling stop() or insertData() without calling start() firstCall start() before other streaming operations
StreamingInProgressStream already in progressCalling start() while another stream is activeStop current stream before starting a new one

Model Execution Errors

These errors come from the ExecuTorch runtime during model execution.

Error CodeDescriptionWhen It OccursHow to Handle
InvalidModelOutputModel output size unexpectedModel produces output of wrong sizeVerify model is compatible with the library
ThreadPoolErrorThreadpool operation failedInternal threading issueRestart the model or app
UnknownErrorUnexpected error occurred3rd-party library error or unhandled exceptionCheck logs for details, report if reproducible

ExecuTorch Runtime Errors

These errors are mapped directly from the ExecuTorch runtime. They typically indicate lower-level execution issues.

System Errors

Error CodeDescription
OkOperation successful (not an error)
InternalInternal ExecuTorch error
InvalidStateOperation called in invalid state
EndOfMethodEnd of method reached

Logical Errors

Error CodeDescription
NotSupportedOperation not supported by model
NotImplementedFeature not implemented
InvalidArgumentInvalid argument passed to operation
InvalidTypeType mismatch in operation
OperatorMissingRequired operator missing from model

Resource Errors

Error CodeDescription
NotFoundResource not found
MemoryAllocationFailedMemory allocation failed
AccessFailedAccess to resource failed
InvalidProgramModel program is invalid
InvalidExternalDataExternal data is invalid
OutOfResourcesSystem resources exhausted

Delegate Errors

Error CodeDescription
DelegateInvalidCompatibilityDelegate not compatible with model
DelegateMemoryAllocationFailedDelegate memory allocation failed
DelegateInvalidHandleInvalid delegate handle