📁 Alternative to Try/catch for JavaScript
npm install @ronaldzav/result-pattern
If you are using yarn:
yarn add @ronaldzav/result-pattern
You can use the latest version of result-pattern
by adding it as a dependency in your package.json
file:
"dependencies": {
"@ronaldzav/result-pattern": "github:ronaldzav/result-pattern"
}
let { Result } = require('@ronaldzav/result-pattern');
function divide(a, b) {
if (b == 0) {
return Result.Failure("Division by zero");
}
return Result.Success(a / b);
}
if (divide(10, 2).isSuccess()) {
console.log("Success:", result1.getValue());
} else {
console.log("Failure:", result1.getError());
}
The Result
class represents a result of a computation that may either be successful or failed.
Returns a successful result with the given value.
Returns a failed result with the given error.
Returns true
if the result is successful, false
otherwise.
Returns true
if the result is failed, false
otherwise.
Returns the value of the successful result, or throws an error if the result is failed.
Returns the error of the failed result, or throws an error if the result is successful.
Copyright 2024 Ronald Zavaleta | Apache-2.0 License | Support