Error Handling
cofhejs uses a consistent error handling pattern based on the Result type to provide predictable and type-safe error handling throughout the library. This guide explains how error handling works and how to properly handle errors in your applications.
Prerequisites
Before handling errors, ensure you understand:- The Result type pattern used throughout Cofhejs
- Basic TypeScript/JavaScript error handling concepts
- How to check for success/failure states
The Result Type
cofhejs uses a functional approach to error handling with the Result type. This pattern avoids exceptions and provides explicit error information.
Result type is a discriminated union that represents either:
- A successful operation with data (
success: true). - A failed operation with an error message (
success: false).
Helper Functions
cofhejs provides two helper functions to create Result objects:
Where Result is Used
Most asynchronous operations incofhejs return a Result type, including:
- Initialization functions (
initializeWithEthers,initializeWithViem,initialize) - Permit operations (
createPermit,getPermit,getPermission) - Encryption and decryption operations
Handling Errors
When working with functions that return aResult, you must always check the success property before accessing the data.
1
Check the success property
Always verify that the operation succeeded before accessing the data.
2
Handle errors appropriately
Provide meaningful error messages and handle failure cases gracefully.
Basic Error Handling Pattern
Error Handling with Destructuring
You can use destructuring to make your code more concise:The permit is created successfully and can be used for subsequent operations.
Common Error Scenarios
Cofhejs may return errors in various scenarios, including:
-
Initialization Errors:
- Missing provider or signer
- Network connectivity issues
- Unsupported environment
-
Permit Errors:
- Invalid permit parameters
- Missing signer
- Unauthorized operations
-
Encryption Errors:
- Missing FHE public key
- Invalid input types
- Network service unavailability
Complete Example
Here’s a complete example of initializingcofhejs and handling potential errors:
Testing Error Cases
When writing tests,cofhejs provides utility functions to validate error results:
Best Practices
-
Always check
success: Never accessdatawithout first verifyingsuccessistrue. - Handle errors explicitly: Provide meaningful error messages to users based on the error type.
-
Use try-catch for unexpected errors: While
cofhejsuses the Result pattern, wrap operations in try-catch blocks to handle unexpected exceptions. - Log errors appropriately: Use appropriate logging levels based on error severity and context.
- Provide user-friendly messages: Translate technical error messages into user-friendly explanations when possible.
success property and appropriately handling errors, you can build robust applications that gracefully handle failure cases when working with cofhejs.