Skip to main content

Either

The either pattern is a design pattern used in object-oriented programming to allow selection between two possible options or states. This pattern is based on the encapsulation principle and promotes loose coupling between the classes or components involved.

The either pattern is commonly used when you have an operation or function that can return one of two different results. Instead of directly returning the result, it is encapsulated in an "either" object that contains information about the result and allows actions to be taken accordingly.

The either object has two possible states: "left" and "right". Each state can contain a different result. For example, in an error handling scenario, the "left" state could contain information about an error that occurred, while the "right" state could contain the expected result.

This pattern allows you to elegantly and efficiently handle situations where you need to consider multiple possible outcomes. Using the either pattern prevents the use of exceptions or special values to represent exceptional conditions, which can improve code readability and maintainability.

info

Most sdk apis use this pattern for error handling.

We can directly access the result of a transaction, for example.

const erc20Api = sdk.transactions.erc20Api
const transaction = await erc20Api.transfer(payload, caller);

const result = transaction.right() // Get the result or undefined

Left

We can access the error of a transaction.

const erc20Api = sdk.transactions.erc20Api
const transaction = await erc20Api.transfer(payload, caller);

const error = transaction.left() // Get the error or undefined

Fold

With this method we have the option of being able to react to both states without using try catch.

const erc20Api = sdk.transactions.erc20Api
const transaction = await erc20Api.transfer(payload, caller);

transaction.fold(
(error) => {
console.log(`Handle error ${error}`);
},
(id) => {
console.log(`Handle transaction ${id}`);
}
);
Try catch

This is not to say that you can't use the try catch statement in your code when using the sdk. What it means is that you are less likely to need to use it to handle exceptions controlled by the sdk. Exceptions are just that, exceptions and you only use this statement to handle exception errors.

Web3 error

Normally the transactions and the use given to either in the sdk are for controlled error handling. And this will return an object with the Web3Error interface.

interface Web3Error {
code: number;
message: string;
}