I am using the Error Handling method using the Result type, which I have posted in this question.
Using the Result type, I could easily build a chain of functions like this
Result.combine(result1, result2)
.onFailure(err => doSomethingOnFailure())
.onSuccess(val => doSomethingOnSuccess())
This flow looks good for me, but I have a problem.
function func(a, b) {
// Some code above
const result = Result.comine(aResult, bResult).onFailure(err => {
// I want to return fail result to the func here but do not know how
}).onSuccess(() => {
// Do something on success
})
// So I have to do a simple if check
if (result.failure) {
// Return fail result here
}
// Then do something on success here
}
I want to return the fail result to the parent function inside the onFailure function.
Could I somehow achieve this?
Instead of writing two separate onFailure and onSuccess methods that just execute a side effect and return the Result instance itself, use a single method for both handlers that returns the result of the respective call:
handle<U>(onSuccess: (value: T) => U, onFailure: (error: string) => U): U {
if (this.success) {
return onSuccess(this._value);
} else {
return onFailure(this.error);
}
}