WHAT YOU'LL LEARN
  • What is the Result?
  • How to use it?
  • How to use the return types?

Overview
anchor

Webiny is utilizing the Result pattern, and there is a Result class that helps with that.

The Result pattern is a way to represent the outcome of an operation that can either succeed or fail. Instead of throwing exceptions, functions return a Result object that encapsulates either a successful value or an error.

Usage
anchor

Let’s say you have a function that performs some async call to an operation which you import from a dependency, and it can either return a result or throw an error.

This way you can be sure that the method does not throw an exception, and you do not have to worry about it down the call stack, which uses the myMethod function.

Return Types
anchor

When using the Result pattern the return types are inferred from the values passed to the Result.ok() and Result.fail() methods.

For example, if you have a function that returns a Result object with a successful value of type string and an error of type Error, the return type would be Result<string, Error>.

For more complex return types, you can define custom types for the success value and error value.

And then you can implement the method like this:

Result Unwrap
anchor

When using Webiny methods and functions that return a Result object, you might want to get the actual value or error types from the Result object.

If the type is not available for you to import, you can use the Result.UnwrapResult and Result.UnwrapError utility to get those types.

For example, using the GetEntryByIdUseCase from Headless CMS:

This can be useful when you want to use return types from Webiny through your own code, but the types are not directly available for import.

Conclusion
anchor

The Result pattern is a powerful way to handle success and failure in your code without relying on exceptions. By using the Result class, you can create functions that return a Result object, making it easier to manage errors and success values in a consistent manner. Additionally, the ability to infer return types from the Result object allows for better type safety and clarity in your code.