Example 3
Read more in https://github.com/sirius-tedarik/sirutils/tree/development/packages/core/src/result
Let's break down the code step by step:
1. Importing Utility Functions
Here, you're importing four utility functions: ProjectError
, wrap
, capsule
, and unwrap
from the @sirutils/core
package. These functions are used for error handling and function encapsulation.
2. Wrapping the getUser
Function
- Purpose: The
getUser
function is wrapped with thewrap
utility to add additional functionality, such as logging or error handling, under the name "?get-user". - Functionality:
- It takes a
name
parameter (expected to be of typeUser["name"]
). - It searches for a user in the
users
array whosename
matches the providedname
. - If the user is not found, it creates and throws a
ProjectError
with the type"?not-found"
and the message"user not found"
. - If the user is found, it returns the user object.
- It takes a
3. Encapsulating the sayHi
Function
- Purpose: The
sayHi
function is encapsulated with thecapsule
utility to similarly add functionality, like error management, under the name "?say-hi". - Functionality:
- It takes a
name
parameter of type string. - It calls the
getUser
function with the providedname
and usesunwrap
to extract the result. If the result is an error,unwrap
would handle that error. - If the user object doesn't have a
surname
, it creates and throws aProjectError
with the type"?unexpected"
and a message indicating the missingsurname
. - If the
surname
is present, it returns a greeting string,Hi {user.name} {user.surname}
.
- It takes a
4. Running the sayHi
Function
- Purpose: This line calls the
sayHi
function with the argument"alice"
and logs the result to the console. - Expected Behavior:
- If a user named "alice" is found and has a
surname
, it will print something likeHi Alice Smith
to the console. - If the user "alice" is not found or if her
surname
is missing, it will throw an error.
- If a user named "alice" is found and has a
Summary
This code demonstrates a structured way of handling errors using custom error objects (ProjectError
), function wrapping (wrap
), and encapsulation (capsule
). The functions are designed to fail gracefully by throwing specific errors when something goes wrong, ensuring that error handling is centralized and consistent across the codebase.