You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+31-1Lines changed: 31 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -38,7 +38,7 @@ The problem with this 'usual' try-catch approach is that:
38
38
- it makes our code harder to reason about. We need to look at implementation details to discover what might go wrong.
39
39
- it makes the control flow of our code harder to reason about, especially with multiple (nested) try-catch statements
40
40
41
-
Instead, we could express the outcome of code to be executed in the form of a Return-type. People using your code will be explicitly confronted with the fact that code potentially might fail, and will know upfront what kind of errors they can expect.
41
+
Instead, we could express the outcome of code to be executed in the form of a Result-type. People using your code will be explicitly confronted with the fact that code potentially might fail, and will know upfront what kind of errors they can expect.
42
42
43
43
## Installation
44
44
@@ -305,6 +305,36 @@ function doB(value: number): Result<ErrorB, string> {}
305
305
const result =doA().map(value=>doB(value)); // Result<ErrorA | ErrorB, string>
306
306
```
307
307
308
+
#### Result.forward()
309
+
310
+
Creates and forwards a brand new Result out of the current error or value.
311
+
This is useful if you want to return early after failure.
312
+
313
+
```ts
314
+
classErrorAextendsError {}
315
+
classErrorBextendsError {}
316
+
317
+
function doA():Result<ErrorA, number> {}
318
+
function doB():Result<ErrorB, number> {}
319
+
320
+
function performAction():Result<ErrorA|ErrorB, number> {
321
+
const resultA =doA();
322
+
if (resultA.isFailure()) {
323
+
returnresultA.forward();
324
+
}
325
+
326
+
const resultB =doA();
327
+
if (resultB.isFailure()) {
328
+
returnresultB.forward();
329
+
}
330
+
331
+
// from here both 'a' and 'b' are valid values
332
+
const [a, b] = [resultA.value, resultB.value];
333
+
334
+
returna+b;
335
+
}
336
+
```
337
+
308
338
## Rollbacks
309
339
310
340
There are cases where a series of operations are performed that need to be treated as a 'unit of work'. In other words: if the last operation fails, de preceding operations should also fail, despite the fact that those preceding operations succeeded on their own. In such cases you probably want some kind of recovering a.k.a. a rollback.
0 commit comments