resultar 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1279 @@
1
+ # Resultar 🙅
2
+
3
+ ## Description
4
+
5
+ Encode failure into your program.
6
+
7
+ This package contains a `Result` type that represents either success (`Ok`) or failure (`Err`).
8
+
9
+ For asynchronous tasks, `resultar` offers a `ResultAsync` class which wraps a `Promise<Result<T, E>>` and gives you the same level of expressivity and control as a regular `Result<T, E>`.
10
+
11
+ `ResultAsync` is `thenable` meaning it **behaves exactly like a native `Promise<Result>`** ... except you have access to the same methods that `Result` provides without having to `await` or `.then` the promise! Check out [the wiki](https://github.com/inaiat/resultar/wiki/Basic-Usage-Examples#asynchronous-api) for examples and best practices.
12
+
13
+ > Need to see real-life examples of how to leverage this package for error handling? See this repo: https://github.com/parlez-vous/server
14
+
15
+ <div id="toc"></div>
16
+
17
+ ## Table Of Contents
18
+
19
+ * [Installation](#installation)
20
+ * [Top-Level API](#top-level-api)
21
+ * [API Documentation](#api-documentation)
22
+ + [Synchronous API (`Result`)](#synchronous-api-result)
23
+ - [`ok`](#ok)
24
+ - [`err`](#err)
25
+ - [`Result.isOk` (method)](#resultisok-method)
26
+ - [`Result.isErr` (method)](#resultiserr-method)
27
+ - [`Result.map` (method)](#resultmap-method)
28
+ - [`Result.mapErr` (method)](#resultmaperr-method)
29
+ - [`Result.unwrapOr` (method)](#resultunwrapor-method)
30
+ - [`Result.andThen` (method)](#resultandthen-method)
31
+ - [`Result.asyncAndThen` (method)](#resultasyncandthen-method)
32
+ - [`Result.orElse` (method)](#resultorelse-method)
33
+ - [`Result.match` (method)](#resultmatch-method)
34
+ - [`Result.asyncMap` (method)](#resultasyncmap-method)
35
+ - [`Result.fromThrowable` (static class method)](#resultfromthrowable-static-class-method)
36
+ - [`Result.combine` (static class method)](#resultcombine-static-class-method)
37
+ - [`Result.combineWithAllErrors` (static class method)](#resultcombinewithallerrors-static-class-method)
38
+ - [`Result.safeUnwrap()`](#resultsafeunwrap)
39
+ + [Asynchronous API (`ResultAsync`)](#asynchronous-api-resultasync)
40
+ - [`okAsync`](#okasync)
41
+ - [`errAsync`](#errasync)
42
+ - [`ResultAsync.fromPromise` (static class method)](#resultasyncfrompromise-static-class-method)
43
+ - [`ResultAsync.fromSafePromise` (static class method)](#resultasyncfromsafepromise-static-class-method)
44
+ - [`ResultAsync.map` (method)](#resultasyncmap-method)
45
+ - [`ResultAsync.mapErr` (method)](#resultasyncmaperr-method)
46
+ - [`ResultAsync.unwrapOr` (method)](#resultasyncunwrapor-method)
47
+ - [`ResultAsync.andThen` (method)](#resultasyncandthen-method)
48
+ - [`ResultAsync.orElse` (method)](#resultasyncorelse-method)
49
+ - [`ResultAsync.match` (method)](#resultasyncmatch-method)
50
+ - [`ResultAsync.combine` (static class method)](#resultasynccombine-static-class-method)
51
+ - [`ResultAsync.combineWithAllErrors` (static class method)](#resultasynccombinewithallerrors-static-class-method)
52
+ - [`ResultAsync.safeUnwrap()`](#resultasyncsafeunwrap)
53
+ + [Utilities](#utilities)
54
+ - [`fromThrowable`](#fromthrowable)
55
+ - [`fromPromise`](#frompromise)
56
+ - [`fromSafePromise`](#fromsafepromise)
57
+ - [`safeTry`](#safetry)
58
+ + [Testing](#testing)
59
+ * [A note on the Package Name](#a-note-on-the-package-name)
60
+
61
+ ## Installation
62
+
63
+ ```sh
64
+ > npm install resultar
65
+ ```
66
+
67
+ ## Top-Level API
68
+
69
+ `resultar` exposes the following:
70
+
71
+ - `ok` convenience function to create an `Ok` variant of `Result`
72
+ - `err` convenience function to create an `Err` variant of `Result`
73
+ - `Ok` class and type
74
+ - `Err` class and type
75
+ - `Result` Type as well as namespace / object from which to call [`Result.fromThrowable`](#resultfromthrowable-static-class-method), [Result.combine](#resultcombine-static-class-method).
76
+ - `ResultAsync` class
77
+ - `okAsync` convenience function to create a `ResultAsync` containing an `Ok` type `Result`
78
+ - `errAsync` convenience function to create a `ResultAsync` containing an `Err` type `Result`
79
+
80
+ ```typescript
81
+ import {
82
+ ok,
83
+ Ok,
84
+ err,
85
+ Err,
86
+ Result,
87
+ okAsync,
88
+ errAsync,
89
+ ResultAsync,
90
+ fromThrowable,
91
+ fromPromise,
92
+ fromSafePromise,
93
+ safeTry,
94
+ } from 'resultar'
95
+ ```
96
+
97
+ ---
98
+
99
+ **Check out the [wiki](https://github.com/inaiat/resultar/wiki) for help on how to make the most of `resultar`.**
100
+
101
+ ---
102
+
103
+ ## API Documentation
104
+
105
+ ### Synchronous API (`Result`)
106
+
107
+ #### `ok`
108
+
109
+ Constructs an `Ok` variant of `Result`
110
+
111
+ **Signature:**
112
+
113
+ ```typescript
114
+ ok<T, E>(value: T): Ok<T, E> { ... }
115
+ ```
116
+
117
+ **Example:**
118
+
119
+ ```typescript
120
+ import { ok } from 'resultar'
121
+
122
+ const myResult = ok({ myData: 'test' }) // instance of `Ok`
123
+
124
+ myResult.isOk() // true
125
+ myResult.isErr() // false
126
+ ```
127
+
128
+ [⬆️ Back to top](#toc)
129
+
130
+ ---
131
+
132
+ #### `err`
133
+
134
+ Constructs an `Err` variant of `Result`
135
+
136
+ **Signature:**
137
+
138
+ ```typescript
139
+ err<T, E>(error: E): Err<T, E> { ... }
140
+ ```
141
+
142
+ **Example:**
143
+
144
+ ```typescript
145
+ import { err } from 'resultar'
146
+
147
+ const myResult = err('Oh noooo') // instance of `Err`
148
+
149
+ myResult.isOk() // false
150
+ myResult.isErr() // true
151
+ ```
152
+
153
+ [⬆️ Back to top](#toc)
154
+
155
+ ---
156
+
157
+ #### `Result.isOk` (method)
158
+
159
+ Returns `true` if the result is an `Ok` variant
160
+
161
+ **Signature:**
162
+
163
+ ```typescript
164
+ isOk(): boolean { ... }
165
+ ```
166
+
167
+ [⬆️ Back to top](#toc)
168
+
169
+ ---
170
+
171
+ #### `Result.isErr` (method)
172
+
173
+ Returns `true` if the result is an `Err` variant
174
+
175
+ **Signature**:
176
+
177
+ ```typescript
178
+ isErr(): boolean { ... }
179
+ ```
180
+
181
+ [⬆️ Back to top](#toc)
182
+
183
+ ---
184
+
185
+ #### `Result.map` (method)
186
+
187
+ Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a contained `Ok` value, leaving an `Err` value untouched.
188
+
189
+ This function can be used to compose the results of two functions.
190
+
191
+ **Signature:**
192
+
193
+ ```typescript
194
+ class Result<T, E> {
195
+ map<U>(callback: (value: T) => U): Result<U, E> { ... }
196
+ }
197
+ ```
198
+
199
+ **Example**:
200
+
201
+ ```typescript
202
+ import { getLines } from 'imaginary-parser'
203
+ // ^ assume getLines has the following signature:
204
+ // getLines(str: string): Result<Array<string>, Error>
205
+
206
+ // since the formatting is deemed correct by `getLines`
207
+ // then it means that `linesResult` is an Ok
208
+ // containing an Array of strings for each line of code
209
+ const linesResult = getLines('1\n2\n3\n4\n')
210
+
211
+ // this Result now has a Array<number> inside it
212
+ const newResult = linesResult.map(
213
+ (arr: Array<string>) => arr.map(parseInt)
214
+ )
215
+
216
+ newResult.isOk() // true
217
+ ```
218
+
219
+ [⬆️ Back to top](#toc)
220
+
221
+ ---
222
+
223
+ #### `Result.mapErr` (method)
224
+
225
+ Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a contained `Err` value, leaving an `Ok` value untouched.
226
+
227
+ This function can be used to pass through a successful result while handling an error.
228
+
229
+ **Signature:**
230
+
231
+ ```typescript
232
+ class Result<T, E> {
233
+ mapErr<F>(callback: (error: E) => F): Result<T, F> { ... }
234
+ }
235
+ ```
236
+
237
+ **Example**:
238
+
239
+ ```typescript
240
+ import { parseHeaders } from 'imaginary-http-parser'
241
+ // imagine that parseHeaders has the following signature:
242
+ // parseHeaders(raw: string): Result<SomeKeyValueMap, ParseError>
243
+
244
+ const rawHeaders = 'nonsensical gibberish and badly formatted stuff'
245
+
246
+ const parseResult = parseHeaders(rawHeaders)
247
+
248
+ parseResult.mapErr(parseError => {
249
+ res.status(400).json({
250
+ error: parseError
251
+ })
252
+ })
253
+
254
+ parseResult.isErr() // true
255
+ ```
256
+
257
+ [⬆️ Back to top](#toc)
258
+
259
+ ---
260
+
261
+ #### `Result.unwrapOr` (method)
262
+
263
+ Unwrap the `Ok` value, or return the default if there is an `Err`
264
+
265
+ **Signature:**
266
+
267
+ ```typescript
268
+ class Result<T, E> {
269
+ unwrapOr<T>(value: T): T { ... }
270
+ }
271
+ ```
272
+
273
+ **Example**:
274
+
275
+ ```typescript
276
+ const myResult = err('Oh noooo')
277
+
278
+ const multiply = (value: number): number => value * 2
279
+
280
+ const unwrapped: number = myResult.map(multiply).unwrapOr(10)
281
+ ```
282
+
283
+ [⬆️ Back to top](#toc)
284
+
285
+ ---
286
+
287
+ #### `Result.andThen` (method)
288
+
289
+ Same idea as `map` above. Except you must return a new `Result`.
290
+
291
+ The returned value will be a `Result`. As of `v4.1.0-beta`, you are able to return distinct error types (see signature below). Prior to `v4.1.0-beta`, the error type could not be distinct.
292
+
293
+ This is useful for when you need to do a subsequent computation using the inner `T` value, but that computation might fail.
294
+
295
+ Additionally, `andThen` is really useful as a tool to flatten a `Result<Result<A, E2>, E1>` into a `Result<A, E2>` (see example below).
296
+
297
+ **Signature:**
298
+
299
+ ```typescript
300
+ class Result<T, E> {
301
+ // Note that the latest version lets you return distinct errors as well.
302
+ // If the error types (E and F) are the same (like `string | string`)
303
+ // then they will be merged into one type (`string`)
304
+ andThen<U, F>(
305
+ callback: (value: T) => Result<U, F>
306
+ ): Result<U, E | F> { ... }
307
+ }
308
+ ```
309
+
310
+ **Example 1: Chaining Results**
311
+
312
+ ```typescript
313
+ import { err, ok } from 'resultar'
314
+
315
+ const sq = (n: number): Result<number, number> => ok(n ** 2)
316
+
317
+ ok(2)
318
+ .andThen(sq)
319
+ .andThen(sq) // Ok(16)
320
+
321
+ ok(2)
322
+ .andThen(sq)
323
+ .andThen(err) // Err(4)
324
+
325
+ ok(2)
326
+ .andThen(err)
327
+ .andThen(sq) // Err(2)
328
+
329
+ err(3)
330
+ .andThen(sq)
331
+ .andThen(sq) // Err(3)
332
+ ```
333
+
334
+ **Example 2: Flattening Nested Results**
335
+
336
+ ```typescript
337
+ // It's common to have nested Results
338
+ const nested = ok(ok(1234))
339
+
340
+ // notNested is a Ok(1234)
341
+ const notNested = nested.andThen((innerResult) => innerResult)
342
+ ```
343
+
344
+ [⬆️ Back to top](#toc)
345
+
346
+ ---
347
+
348
+ #### `Result.asyncAndThen` (method)
349
+
350
+ Same idea as [`andThen` above](#resultandthen-method), except you must return a new `ResultAsync`.
351
+
352
+ The returned value will be a `ResultAsync`.
353
+
354
+ **Signature:**
355
+
356
+ ```typescript
357
+ class Result<T, E> {
358
+ asyncAndThen<U, F>(
359
+ callback: (value: T) => ResultAsync<U, F>
360
+ ): ResultAsync<U, E | F> { ... }
361
+ }
362
+ ```
363
+
364
+ [⬆️ Back to top](#toc)
365
+
366
+ ---
367
+
368
+ #### `Result.orElse` (method)
369
+
370
+ Takes an `Err` value and maps it to a `Result<T, SomeNewType>`. This is useful for error recovery.
371
+
372
+ **Signature:**
373
+
374
+ ```typescript
375
+ class Result<T, E> {
376
+ orElse<A>(
377
+ callback: (error: E) => Result<T, A>
378
+ ): Result<T, A> { ... }
379
+ }
380
+ ```
381
+
382
+ **Example:**
383
+
384
+ ```typescript
385
+ enum DatabaseError {
386
+ PoolExhausted = 'PoolExhausted',
387
+ NotFound = 'NotFound',
388
+ }
389
+
390
+ const dbQueryResult: Result<string, DatabaseError> = err(DatabaseError.NotFound)
391
+
392
+ const updatedQueryResult = dbQueryResult.orElse((dbError) =>
393
+ dbError === DatabaseError.NotFound
394
+ ? ok('User does not exist') // error recovery branch: ok() must be called with a value of type string
395
+ //
396
+ //
397
+ // err() can be called with a value of any new type that you want
398
+ // it could also be called with the same error value
399
+ //
400
+ // err(dbError)
401
+ : err(500)
402
+ )
403
+ ```
404
+
405
+ [⬆️ Back to top](#toc)
406
+
407
+ ---
408
+
409
+ #### `Result.match` (method)
410
+
411
+ Given 2 functions (one for the `Ok` variant and one for the `Err` variant) execute the function that matches the `Result` variant.
412
+
413
+ Match callbacks do not necessitate to return a `Result`, however you can return a `Result` if you want to.
414
+
415
+ **Signature:**
416
+
417
+ ```typescript
418
+ class Result<T, E> {
419
+ match<A>(
420
+ okCallback: (value: T) => A,
421
+ errorCallback: (error: E) => A
422
+ ): A => { ... }
423
+ }
424
+ ```
425
+
426
+ `match` is like chaining `map` and `mapErr`, with the distinction that with `match` both functions must have the same return type.
427
+ The differences between `match` and chaining `map` and `mapErr` are that:
428
+ - with `match` both functions must have the same return type `A`
429
+ - `match` unwraps the `Result<T, E>` into an `A` (the match functions' return type)
430
+ - This makes no difference if you are performing side effects only
431
+
432
+ **Example:**
433
+
434
+ ```typescript
435
+ // map/mapErr api
436
+ // note that you DON'T have to append mapErr
437
+ // after map which means that you are not required to do
438
+ // error handling
439
+ computationThatMightFail().map(console.log).mapErr(console.error)
440
+
441
+ // match api
442
+ // works exactly the same as above since both callbacks
443
+ // only perform side effects,
444
+ // except, now you HAVE to do error handling :)
445
+ computationThatMightFail().match(console.log, console.error)
446
+
447
+ // Returning values
448
+ const attempt = computationThatMightFail()
449
+ .map((str) => str.toUpperCase())
450
+ .mapErr((err) => `Error: ${err}`)
451
+ // `attempt` is of type `Result<string, string>`
452
+
453
+ const answer = computationThatMightFail().match(
454
+ (str) => str.toUpperCase(),
455
+ (err) => `Error: ${err}`
456
+ )
457
+ // `answer` is of type `string`
458
+ ```
459
+
460
+ If you don't use the error parameter in your match callback then `match` is equivalent to chaining `map` with `unwrapOr`:
461
+ ```ts
462
+ const answer = computationThatMightFail().match(
463
+ (str) => str.toUpperCase(),
464
+ () => 'ComputationError'
465
+ )
466
+ // `answer` is of type `string`
467
+
468
+ const answer = computationThatMightFail()
469
+ .map((str) => str.toUpperCase())
470
+ .unwrapOr('ComputationError')
471
+ ```
472
+
473
+
474
+ [⬆️ Back to top](#toc)
475
+
476
+ ---
477
+
478
+ #### `Result.asyncMap` (method)
479
+
480
+ Similar to `map` except for two things:
481
+
482
+ - the mapping function must return a `Promise`
483
+ - asyncMap returns a `ResultAsync`
484
+
485
+ You can then chain the result of `asyncMap` using the `ResultAsync` apis (like `map`, `mapErr`, `andThen`, etc.)
486
+
487
+ **Signature:**
488
+
489
+ ```typescript
490
+ class Result<T, E> {
491
+ asyncMap<U>(
492
+ callback: (value: T) => Promise<U>
493
+ ): ResultAsync<U, E> { ... }
494
+ }
495
+ ```
496
+
497
+ **Example:**
498
+
499
+ ```typescript
500
+ import { parseHeaders } from 'imaginary-http-parser'
501
+ // imagine that parseHeaders has the following signature:
502
+ // parseHeaders(raw: string): Result<SomeKeyValueMap, ParseError>
503
+
504
+ const asyncRes = parseHeaders(rawHeader)
505
+ .map(headerKvMap => headerKvMap.Authorization)
506
+ .asyncMap(findUserInDatabase)
507
+ ```
508
+
509
+ Note that in the above example if `parseHeaders` returns an `Err` then `.map` and `.asyncMap` will not be invoked, and `asyncRes` variable will resolve to an `Err` when turned into a `Result` using `await` or `.then()`.
510
+
511
+ [⬆️ Back to top](#toc)
512
+
513
+ ---
514
+
515
+ #### `Result.fromThrowable` (static class method)
516
+
517
+ > Although Result is not an actual JS class, the way that `fromThrowable` has been implemented requires that you call `fromThrowable` as though it were a static method on `Result`. See examples below.
518
+
519
+ The JavaScript community has agreed on the convention of throwing exceptions.
520
+ As such, when interfacing with third party libraries it's imperative that you
521
+ wrap third-party code in try / catch blocks.
522
+
523
+ This function will create a new function that returns an `Err` when the original
524
+ function throws.
525
+
526
+ It is not possible to know the types of the errors thrown in the original
527
+ function, therefore it is recommended to use the second argument `errorFn` to
528
+ map what is thrown to a known type.
529
+
530
+ **Example**:
531
+
532
+ ```typescript
533
+ import { Result } from 'resultar'
534
+
535
+ type ParseError = { message: string }
536
+ const toParseError = (): ParseError => ({ message: "Parse Error" })
537
+
538
+ const safeJsonParse = Result.fromThrowable(JSON.parse, toParseError)
539
+
540
+ // the function can now be used safely, if the function throws, the result will be an Err
541
+ const res = safeJsonParse("{");
542
+ ```
543
+
544
+ [⬆️ Back to top](#toc)
545
+
546
+ ---
547
+
548
+ #### `Result.combine` (static class method)
549
+
550
+ > Although Result is not an actual JS class, the way that `combine` has been implemented requires that you call `combine` as though it were a static method on `Result`. See examples below.
551
+
552
+ Combine lists of `Result`s.
553
+
554
+ If you're familiar with `Promise.all`, the combine function works conceptually the same.
555
+
556
+ **`combine` works on both heterogeneous and homogeneous lists**. This means that you can have lists that contain different kinds of `Result`s and still be able to combine them. Note that you cannot combine lists that contain both `Result`s **and** `ResultAsync`s.
557
+
558
+ The combine function takes a list of results and returns a single result. If all the results in the list are `Ok`, then the return value will be a `Ok` containing a list of all the individual `Ok` values.
559
+
560
+ If just one of the results in the list is an `Err` then the combine function returns that Err value (it short circuits and returns the first Err that it finds).
561
+
562
+ Formally speaking:
563
+
564
+ ```typescript
565
+ // homogeneous lists
566
+ function combine<T, E>(resultList: Result<T, E>[]): Result<T[], E>
567
+
568
+ // heterogeneous lists
569
+ function combine<T1, T2, E1, E2>(resultList: [ Result<T1, E1>, Result<T2, E2> ]): Result<[ T1, T2 ], E1 | E2>
570
+ function combine<T1, T2, T3, E1, E2, E3> => Result<[ T1, T2, T3 ], E1 | E2 | E3>
571
+ function combine<T1, T2, T3, T4, E1, E2, E3, E4> => Result<[ T1, T2, T3, T4 ], E1 | E2 | E3 | E4>
572
+ // ... etc etc ad infinitum
573
+
574
+ ```
575
+
576
+ Example:
577
+ ```typescript
578
+ const resultList: Result<number, never>[] =
579
+ [ok(1), ok(2)]
580
+
581
+ const combinedList: Result<number[], unknown> =
582
+ Result.combine(resultList)
583
+ ```
584
+
585
+ Example with tuples:
586
+ ```typescript
587
+ /** @example tuple(1, 2, 3) === [1, 2, 3] // with type [number, number, number] */
588
+ const tuple = <T extends any[]>(...args: T): T => args
589
+
590
+ const resultTuple: [Result<string, never>, Result<string, never>] =
591
+ tuple(ok('a'), ok('b'))
592
+
593
+ const combinedTuple: Result<[string, string], unknown> =
594
+ Result.combine(resultTuple)
595
+ ```
596
+
597
+ [⬆️ Back to top](#toc)
598
+
599
+ ---
600
+
601
+ #### `Result.combineWithAllErrors` (static class method)
602
+
603
+ > Although Result is not an actual JS class, the way that `combineWithAllErrors` has been implemented requires that you call `combineWithAllErrors` as though it were a static method on `Result`. See examples below.
604
+
605
+ Like `combine` but without short-circuiting. Instead of just the first error value, you get a list of all error values of the input result list.
606
+
607
+ If only some results fail, the new combined error list will only contain the error value of the failed results, meaning that there is no guarantee of the length of the new error list.
608
+
609
+ Function signature:
610
+
611
+ ```typescript
612
+ // homogeneous lists
613
+ function combineWithAllErrors<T, E>(resultList: Result<T, E>[]): Result<T[], E[]>
614
+
615
+ // heterogeneous lists
616
+ function combineWithAllErrors<T1, T2, E1, E2>(resultList: [ Result<T1, E1>, Result<T2, E2> ]): Result<[ T1, T2 ], (E1 | E2)[]>
617
+ function combineWithAllErrors<T1, T2, T3, E1, E2, E3> => Result<[ T1, T2, T3 ], (E1 | E2 | E3)[]>
618
+ function combineWithAllErrors<T1, T2, T3, T4, E1, E2, E3, E4> => Result<[ T1, T2, T3, T4 ], (E1 | E2 | E3 | E4)[]>
619
+ // ... etc etc ad infinitum
620
+ ```
621
+
622
+ Example usage:
623
+
624
+ ```typescript
625
+ const resultList: Result<number, string>[] = [
626
+ ok(123),
627
+ err('boooom!'),
628
+ ok(456),
629
+ err('ahhhhh!'),
630
+ ]
631
+
632
+ const result = Result.combineWithAllErrors(resultList)
633
+
634
+ // result is Err(['boooom!', 'ahhhhh!'])
635
+ ```
636
+
637
+ [⬆️ Back to top](#toc)
638
+
639
+ #### `Result.safeUnwrap()`
640
+
641
+ **⚠️ You must use `.safeUnwrap` in a generator context with `safeTry`**. Please see [safeTry](#safeTry).
642
+
643
+ Allows for unwrapping a `Result` or returning an `Err` implicitly, thereby reducing boilerplate.
644
+
645
+
646
+ [⬆️ Back to top](#toc)
647
+
648
+ ---
649
+
650
+ ### Asynchronous API (`ResultAsync`)
651
+
652
+ #### `okAsync`
653
+
654
+ Constructs an `Ok` variant of `ResultAsync`
655
+
656
+ **Signature:**
657
+
658
+ ```typescript
659
+ okAsync<T, E>(value: T): ResultAsync<T, E>
660
+ ```
661
+
662
+ **Example:**
663
+
664
+ ```typescript
665
+ import { okAsync } from 'resultar'
666
+
667
+ const myResultAsync = okAsync({ myData: 'test' }) // instance of `ResultAsync`
668
+
669
+ const myResult = await myResultAsync // instance of `Ok`
670
+
671
+ myResult.isOk() // true
672
+ myResult.isErr() // false
673
+ ```
674
+
675
+ [⬆️ Back to top](#toc)
676
+
677
+ ---
678
+
679
+ #### `errAsync`
680
+
681
+ Constructs an `Err` variant of `ResultAsync`
682
+
683
+ **Signature:**
684
+
685
+ ```typescript
686
+ errAsync<T, E>(error: E): ResultAsync<T, E>
687
+ ```
688
+
689
+ **Example:**
690
+
691
+ ```typescript
692
+ import { errAsync } from 'resultar'
693
+
694
+ const myResultAsync = errAsync('Oh nooo') // instance of `ResultAsync`
695
+
696
+ const myResult = await myResultAsync // instance of `Err`
697
+
698
+ myResult.isOk() // false
699
+ myResult.isErr() // true
700
+ ```
701
+
702
+ [⬆️ Back to top](#toc)
703
+
704
+ ---
705
+
706
+ #### `ResultAsync.fromPromise` (static class method)
707
+
708
+ Transforms a `PromiseLike<T>` (that may throw) into a `ResultAsync<T, E>`.
709
+
710
+ The second argument handles the rejection case of the promise and maps the error from `unknown` into some type `E`.
711
+
712
+
713
+ **Signature:**
714
+
715
+ ```typescript
716
+ // fromPromise is a static class method
717
+ // also available as a standalone function
718
+ // import { fromPromise } from 'resultar'
719
+ ResultAsync.fromPromise<T, E>(
720
+ promise: PromiseLike<T>,
721
+ errorHandler: (unknownError: unknown) => E)
722
+ ): ResultAsync<T, E> { ... }
723
+ ```
724
+
725
+ If you are working with `PromiseLike` objects that you **know for a fact** will not throw, then use `fromSafePromise` in order to avoid having to pass a redundant `errorHandler` argument.
726
+
727
+ **Example**:
728
+
729
+ ```typescript
730
+ import { ResultAsync } from 'resultar'
731
+ import { insertIntoDb } from 'imaginary-database'
732
+ // insertIntoDb(user: User): Promise<User>
733
+
734
+ const res = ResultAsync.fromPromise(insertIntoDb(myUser), () => new Error('Database error'))
735
+ // `res` has a type of ResultAsync<User, Error>
736
+ ```
737
+
738
+ [⬆️ Back to top](#toc)
739
+
740
+ ---
741
+
742
+ #### `ResultAsync.fromSafePromise` (static class method)
743
+
744
+ Same as `ResultAsync.fromPromise` except that it does not handle the rejection of the promise. **Ensure you know what you're doing, otherwise a thrown exception within this promise will cause ResultAsync to reject, instead of resolve to a Result.**
745
+
746
+ **Signature:**
747
+
748
+ ```typescript
749
+ // fromPromise is a static class method
750
+ // also available as a standalone function
751
+ // import { fromPromise } from 'resultar'
752
+ ResultAsync.fromSafePromise<T, E>(
753
+ promise: PromiseLike<T>
754
+ ): ResultAsync<T, E> { ... }
755
+ ```
756
+
757
+ **Example**:
758
+
759
+ ```typescript
760
+ import { RouteError } from 'routes/error'
761
+
762
+ // simulate slow routes in an http server that works in a Result / ResultAsync context
763
+ // Adopted from https://github.com/parlez-vous/server/blob/2496bacf55a2acbebc30631b5562f34272794d76/src/routes/common/signup.ts
764
+ export const slowDown = <T>(ms: number) => (value: T) =>
765
+ ResultAsync.fromSafePromise<T, RouteError>(
766
+ new Promise((resolve) => {
767
+ setTimeout(() => {
768
+ resolve(value)
769
+ }, ms)
770
+ })
771
+ )
772
+
773
+ export const signupHandler = route<User>((req, sessionManager) =>
774
+ decode(userSignupDecoder, req.body, 'Invalid request body').map((parsed) => {
775
+ return createUser(parsed)
776
+ .andThen(slowDown(3000)) // slowdown by 3 seconds
777
+ .andThen(sessionManager.createSession)
778
+ .map(({ sessionToken, admin }) => AppData.init(admin, sessionToken))
779
+ })
780
+ )
781
+ ```
782
+
783
+
784
+ [⬆️ Back to top](#toc)
785
+
786
+ ---
787
+
788
+ #### `ResultAsync.map` (method)
789
+
790
+ Maps a `ResultAsync<T, E>` to `ResultAsync<U, E>` by applying a function to a contained `Ok` value, leaving an `Err` value untouched.
791
+
792
+ The applied function can be synchronous or asynchronous (returning a `Promise<U>`) with no impact to the return type.
793
+
794
+ This function can be used to compose the results of two functions.
795
+
796
+ **Signature:**
797
+
798
+ ```typescript
799
+ class ResultAsync<T, E> {
800
+ map<U>(
801
+ callback: (value: T) => U | Promise<U>
802
+ ): ResultAsync<U, E> { ... }
803
+ }
804
+ ```
805
+
806
+ **Example**:
807
+
808
+ ```typescript
809
+ import { findUsersIn } from 'imaginary-database'
810
+ // ^ assume findUsersIn has the following signature:
811
+ // findUsersIn(country: string): ResultAsync<Array<User>, Error>
812
+
813
+ const usersInCanada = findUsersIn("Canada")
814
+
815
+ // Let's assume we only need their names
816
+ const namesInCanada = usersInCanada.map((users: Array<User>) => users.map(user => user.name))
817
+ // namesInCanada is of type ResultAsync<Array<string>, Error>
818
+
819
+ // We can extract the Result using .then() or await
820
+ namesInCanada.then((namesResult: Result<Array<string>, Error>) => {
821
+ if(namesResult.isErr()){
822
+ console.log("Couldn't get the users from the database", namesResult.error)
823
+ }
824
+ else{
825
+ console.log("Users in Canada are named: " + namesResult.value.join(','))
826
+ }
827
+ })
828
+ ```
829
+
830
+ [⬆️ Back to top](#toc)
831
+
832
+ ---
833
+
834
+ #### `ResultAsync.mapErr` (method)
835
+
836
+ Maps a `ResultAsync<T, E>` to `ResultAsync<T, F>` by applying a function to a contained `Err` value, leaving an `Ok` value untouched.
837
+
838
+ The applied function can be synchronous or asynchronous (returning a `Promise<F>`) with no impact to the return type.
839
+
840
+ This function can be used to pass through a successful result while handling an error.
841
+
842
+ **Signature:**
843
+
844
+ ```typescript
845
+ class ResultAsync<T, E> {
846
+ mapErr<F>(
847
+ callback: (error: E) => F | Promise<F>
848
+ ): ResultAsync<T, F> { ... }
849
+ }
850
+ ```
851
+
852
+ **Example**:
853
+
854
+ ```typescript
855
+ import { findUsersIn } from 'imaginary-database'
856
+ // ^ assume findUsersIn has the following signature:
857
+ // findUsersIn(country: string): ResultAsync<Array<User>, Error>
858
+
859
+ // Let's say we need to low-level errors from findUsersIn to be more readable
860
+ const usersInCanada = findUsersIn("Canada").mapErr((error: Error) => {
861
+ // The only error we want to pass to the user is "Unknown country"
862
+ if(error.message === "Unknown country"){
863
+ return error.message
864
+ }
865
+ // All other errors will be labelled as a system error
866
+ return "System error, please contact an administrator."
867
+ })
868
+
869
+ // usersInCanada is of type ResultAsync<Array<User>, string>
870
+
871
+ usersInCanada.then((usersResult: Result<Array<User>, string>) => {
872
+ if(usersResult.isErr()){
873
+ res.status(400).json({
874
+ error: usersResult.error
875
+ })
876
+ }
877
+ else{
878
+ res.status(200).json({
879
+ users: usersResult.value
880
+ })
881
+ }
882
+ })
883
+ ```
884
+
885
+ [⬆️ Back to top](#toc)
886
+
887
+ ---
888
+
889
+ #### `ResultAsync.unwrapOr` (method)
890
+
891
+ Unwrap the `Ok` value, or return the default if there is an `Err`.
892
+ Works just like `Result.unwrapOr` but returns a `Promise<T>` instead of `T`.
893
+
894
+ **Signature:**
895
+
896
+ ```typescript
897
+ class ResultAsync<T, E> {
898
+ unwrapOr<T>(value: T): Promise<T> { ... }
899
+ }
900
+ ```
901
+
902
+ **Example**:
903
+
904
+ ```typescript
905
+ const unwrapped: number = await errAsync(0).unwrapOr(10)
906
+ // unwrapped = 10
907
+ ```
908
+
909
+ [⬆️ Back to top](#toc)
910
+
911
+ ---
912
+
913
+ #### `ResultAsync.andThen` (method)
914
+
915
+ Same idea as `map` above. Except the applied function must return a `Result` or `ResultAsync`.
916
+
917
+ `ResultAsync.andThen` always returns a `ResultAsync` no matter the return type of the applied function.
918
+
919
+ This is useful for when you need to do a subsequent computation using the inner `T` value, but that computation might fail.
920
+
921
+ `andThen` is really useful as a tool to flatten a `ResultAsync<ResultAsync<A, E2>, E1>` into a `ResultAsync<A, E2>` (see example below).
922
+
923
+ **Signature:**
924
+
925
+ ```typescript
926
+ // Note that the latest version (v4.1.0-beta) lets you return distinct errors as well.
927
+ // If the error types (E and F) are the same (like `string | string`)
928
+ // then they will be merged into one type (`string`)
929
+
930
+ class ResultAsync<T, E> {
931
+ andThen<U, F>(
932
+ callback: (value: T) => Result<U, F> | ResultAsync<U, F>
933
+ ): ResultAsync<U, E | F> { ... }
934
+ }
935
+ ```
936
+
937
+ **Example**
938
+
939
+ ```typescript
940
+
941
+ import { validateUser } from 'imaginary-validator'
942
+ import { insertUser } from 'imaginary-database'
943
+ import { sendNotification } from 'imaginary-service'
944
+
945
+ // ^ assume validateUser, insertUser and sendNotification have the following signatures:
946
+ // validateUser(user: User): Result<User, Error>
947
+ // insertUser(user): ResultAsync<User, Error>
948
+ // sendNotification(user): ResultAsync<void, Error>
949
+
950
+ const resAsync = validateUser(user)
951
+ .andThen(insertUser)
952
+ .andThen(sendNotification)
953
+
954
+ // resAsync is a ResultAsync<void, Error>
955
+
956
+ resAsync.then((res: Result<void, Error>) => {
957
+ if(res.isErr()){
958
+ console.log("Oops, at least one step failed", res.error)
959
+ }
960
+ else{
961
+ console.log("User has been validated, inserted and notified successfully.")
962
+ }
963
+ })
964
+ ```
965
+
966
+ [⬆️ Back to top](#toc)
967
+
968
+ ---
969
+
970
+ #### `ResultAsync.orElse` (method)
971
+
972
+ Takes an `Err` value and maps it to a `ResultAsync<T, SomeNewType>`. This is useful for error recovery.
973
+
974
+ **Signature:**
975
+
976
+ ```typescript
977
+ class ResultAsync<T, E> {
978
+ orElse<A>(
979
+ callback: (error: E) => Result<T, A> | ResultAsync<T, A>
980
+ ): ResultAsync<T, A> { ... }
981
+ }
982
+ ```
983
+
984
+ [⬆️ Back to top](#toc)
985
+
986
+ ---
987
+
988
+ #### `ResultAsync.match` (method)
989
+
990
+ Given 2 functions (one for the `Ok` variant and one for the `Err` variant) execute the function that matches the `ResultAsync` variant.
991
+
992
+ The difference with `Result.match` is that it always returns a `Promise` because of the asynchronous nature of the `ResultAsync`.
993
+
994
+ **Signature:**
995
+
996
+ ```typescript
997
+ class ResultAsync<T, E> {
998
+ match<A>(
999
+ okCallback: (value: T) => A,
1000
+ errorCallback: (error: E) => A
1001
+ ): Promise<A> => { ... }
1002
+ }
1003
+ ```
1004
+
1005
+ **Example:**
1006
+
1007
+ ```typescript
1008
+
1009
+ import { validateUser } from 'imaginary-validator'
1010
+ import { insertUser } from 'imaginary-database'
1011
+
1012
+ // ^ assume validateUser and insertUser have the following signatures:
1013
+ // validateUser(user: User): Result<User, Error>
1014
+ // insertUser(user): ResultAsync<User, Error>
1015
+
1016
+ // Handle both cases at the end of the chain using match
1017
+ const resultMessage = await validateUser(user)
1018
+ .andThen(insertUser)
1019
+ .match(
1020
+ (user: User) => `User ${user.name} has been successfully created`,
1021
+ (error: Error) => `User could not be created because ${error.message}`
1022
+ )
1023
+
1024
+ // resultMessage is a string
1025
+ ```
1026
+
1027
+ [⬆️ Back to top](#toc)
1028
+
1029
+ ---
1030
+
1031
+ #### `ResultAsync.combine` (static class method)
1032
+
1033
+ Combine lists of `ResultAsync`s.
1034
+
1035
+ If you're familiar with `Promise.all`, the combine function works conceptually the same.
1036
+
1037
+ **`combine` works on both heterogeneous and homogeneous lists**. This means that you can have lists that contain different kinds of `ResultAsync`s and still be able to combine them. Note that you cannot combine lists that contain both `Result`s **and** `ResultAsync`s.
1038
+
1039
+ The combine function takes a list of results and returns a single result. If all the results in the list are `Ok`, then the return value will be a `Ok` containing a list of all the individual `Ok` values.
1040
+
1041
+ If just one of the results in the list is an `Err` then the combine function returns that Err value (it short circuits and returns the first Err that it finds).
1042
+
1043
+ Formally speaking:
1044
+
1045
+ ```typescript
1046
+ // homogeneous lists
1047
+ function combine<T, E>(resultList: ResultAsync<T, E>[]): ResultAsync<T[], E>
1048
+
1049
+ // heterogeneous lists
1050
+ function combine<T1, T2, E1, E2>(resultList: [ ResultAsync<T1, E1>, ResultAsync<T2, E2> ]): ResultAsync<[ T1, T2 ], E1 | E2>
1051
+ function combine<T1, T2, T3, E1, E2, E3> => ResultAsync<[ T1, T2, T3 ], E1 | E2 | E3>
1052
+ function combine<T1, T2, T3, T4, E1, E2, E3, E4> => ResultAsync<[ T1, T2, T3, T4 ], E1 | E2 | E3 | E4>
1053
+ // ... etc etc ad infinitum
1054
+
1055
+ ```
1056
+
1057
+ Example:
1058
+ ```typescript
1059
+ const resultList: ResultAsync<number, never>[] =
1060
+ [okAsync(1), okAsync(2)]
1061
+
1062
+ const combinedList: ResultAsync<number[], unknown> =
1063
+ ResultAsync.combine(resultList)
1064
+ ```
1065
+
1066
+ Example with tuples:
1067
+ ```typescript
1068
+ /** @example tuple(1, 2, 3) === [1, 2, 3] // with type [number, number, number] */
1069
+ const tuple = <T extends any[]>(...args: T): T => args
1070
+
1071
+ const resultTuple: [ResultAsync<string, never>, ResultAsync<string, never>] =
1072
+ tuple(okAsync('a'), okAsync('b'))
1073
+
1074
+ const combinedTuple: ResultAsync<[string, string], unknown> =
1075
+ ResultAsync.combine(resultTuple)
1076
+ ```
1077
+ [⬆️ Back to top](#toc)
1078
+
1079
+ ---
1080
+
1081
+ #### `ResultAsync.combineWithAllErrors` (static class method)
1082
+
1083
+ Like `combine` but without short-circuiting. Instead of just the first error value, you get a list of all error values of the input result list.
1084
+
1085
+ If only some results fail, the new combined error list will only contain the error value of the failed results, meaning that there is no guarantee of the length of the new error list.
1086
+
1087
+ Function signature:
1088
+
1089
+ ```typescript
1090
+ // homogeneous lists
1091
+ function combineWithAllErrors<T, E>(resultList: ResultAsync<T, E>[]): ResultAsync<T[], E[]>
1092
+
1093
+ // heterogeneous lists
1094
+ function combineWithAllErrors<T1, T2, E1, E2>(resultList: [ ResultAsync<T1, E1>, ResultAsync<T2, E2> ]): ResultAsync<[ T1, T2 ], (E1 | E2)[]>
1095
+ function combineWithAllErrors<T1, T2, T3, E1, E2, E3> => ResultAsync<[ T1, T2, T3 ], (E1 | E2 | E3)[]>
1096
+ function combineWithAllErrors<T1, T2, T3, T4, E1, E2, E3, E4> => ResultAsync<[ T1, T2, T3, T4 ], (E1 | E2 | E3 | E4)[]>
1097
+ // ... etc etc ad infinitum
1098
+ ```
1099
+
1100
+ Example usage:
1101
+
1102
+ ```typescript
1103
+ const resultList: ResultAsync<number, string>[] = [
1104
+ okAsync(123),
1105
+ errAsync('boooom!'),
1106
+ okAsync(456),
1107
+ errAsync('ahhhhh!'),
1108
+ ]
1109
+
1110
+ const result = ResultAsync.combineWithAllErrors(resultList)
1111
+
1112
+ // result is Err(['boooom!', 'ahhhhh!'])
1113
+ ```
1114
+
1115
+ #### `ResultAsync.safeUnwrap()`
1116
+
1117
+ **⚠️ You must use `.safeUnwrap` in a generator context with `safeTry`**. Please see [safeTry](#safeTry).
1118
+
1119
+ Allows for unwrapping a `Result` or returning an `Err` implicitly, thereby reducing boilerplate.
1120
+
1121
+ [⬆️ Back to top](#toc)
1122
+
1123
+ ---
1124
+
1125
+ ### Utilities
1126
+
1127
+ #### `fromThrowable`
1128
+
1129
+ Top level export of `Result.fromThrowable`.
1130
+ Please find documentation at [Result.fromThrowable](#resultfromthrowable-static-class-method)
1131
+
1132
+ [⬆️ Back to top](#toc)
1133
+
1134
+ #### `fromPromise`
1135
+
1136
+ Top level export of `ResultAsync.fromPromise`.
1137
+ Please find documentation at [ResultAsync.fromPromise](#resultasyncfrompromise-static-class-method)
1138
+
1139
+ [⬆️ Back to top](#toc)
1140
+
1141
+ #### `fromSafePromise`
1142
+
1143
+ Top level export of `ResultAsync.fromSafePromise`.
1144
+ Please find documentation at [ResultAsync.fromSafePromise](#resultasyncfromsafepromise-static-class-method)
1145
+
1146
+ [⬆️ Back to top](#toc)
1147
+
1148
+
1149
+ #### `safeTry`
1150
+
1151
+ Used to implicityly return errors and reduce boilerplate.
1152
+
1153
+ Let's say we are writing a function that returns a `Result`, and in that function we call some functions which also return `Result`s and we check those results to see whether we shold keep going or abort. Usually, we will write like the following.
1154
+ ```typescript
1155
+ declare function mayFail1(): Result<number, string>;
1156
+ declare function mayFail2(): Result<number, string>;
1157
+
1158
+ function myFunc(): Result<number, string> {
1159
+ // We have to define a constant to hold the result to check and unwrap its value.
1160
+ const result1 = mayFail1();
1161
+ if (result1.isErr()) {
1162
+ return err(`aborted by an error from 1st function, ${result1.error}`);
1163
+ }
1164
+ const value1 = result1.value
1165
+
1166
+ // Again, we need to define a constant and then check and unwrap.
1167
+ const result2 = mayFail2();
1168
+ if (result2.isErr()) {
1169
+ return err(`aborted by an error from 2nd function, ${result2.error}`);
1170
+ }
1171
+ const value2 = result2.value
1172
+
1173
+ // And finally we return what we want to calculate
1174
+ return ok(value1 + value2);
1175
+ }
1176
+ ```
1177
+ Basically, we need to define a constant for each result to check whether it's a `Ok` and read its `.value` or `.error`.
1178
+
1179
+ With safeTry, we can state 'Return here if its an `Err`, otherwise unwrap it here and keep going.' in just one expression.
1180
+ ```typescript
1181
+ declare function mayFail1(): Result<number, string>;
1182
+ declare function mayFail2(): Result<number, string>;
1183
+
1184
+ function myFunc(): Result<number, string> {
1185
+ return safeTry<number, string>(function*() {
1186
+ return ok(
1187
+ // If the result of mayFail1().mapErr() is an `Err`, the evaluation is
1188
+ // aborted here and the enclosing `safeTry` block is evaluated to that `Err`.
1189
+ // Otherwise, this `(yield* ...)` is evaluated to its `.value`.
1190
+ (yield* mayFail1()
1191
+ .mapErr(e => `aborted by an error from 1st function, ${e}`)
1192
+ .safeUnwrap())
1193
+ +
1194
+ // The same as above.
1195
+ (yield* mayFail2()
1196
+ .mapErr(e => `aborted by an error from 2nd function, ${e}`)
1197
+ .safeUnwrap())
1198
+ )
1199
+ })
1200
+ }
1201
+ ```
1202
+
1203
+ To use `safeTry`, the points are as follows.
1204
+ * Wrap the entire block in a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)
1205
+ * In that block, you can use `yield* <RESULT>` to state 'Return `<RESULT>` if it's an `Err`, otherwise evaluate to its `.value`'
1206
+ * Pass the generator function to `safeTry`
1207
+
1208
+ You can also use [async generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) to pass an async block to `safeTry`.
1209
+ ```typescript
1210
+ // You can use either Promise<Result> or ResultAsync.
1211
+ declare function mayFail1(): Promise<Result<number, string>>;
1212
+ declare function mayFail2(): ResultAsync<number, string>;
1213
+
1214
+ function myFunc(): Promise<Result<number, string>> {
1215
+ return safeTry<number, string>(async function*() {
1216
+ return ok(
1217
+ // You have to await if the expression is Promise<Result>
1218
+ (yield* (await mayFail1())
1219
+ .mapErr(e => `aborted by an error from 1st function, ${e}`)
1220
+ .safeUnwrap())
1221
+ +
1222
+ // You can call `safeUnwrap` directly if its ResultAsync
1223
+ (yield* mayFail2()
1224
+ .mapErr(e => `aborted by an error from 2nd function, ${e}`)
1225
+ .safeUnwrap())
1226
+ )
1227
+ })
1228
+ }
1229
+ ```
1230
+
1231
+ For more information, see https://github.com/supermacro/neverthrow/pull/448 and https://github.com/supermacro/neverthrow/issues/444
1232
+
1233
+ [⬆️ Back to top](#toc)
1234
+
1235
+ ---
1236
+
1237
+ ### Testing
1238
+
1239
+ `Result` instances have two unsafe methods, aptly called `_unsafeUnwrap` and `_unsafeUnwrapErr` which **should only be used in a test environment**.
1240
+
1241
+ `_unsafeUnwrap` takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.
1242
+
1243
+ `_unsafeUnwrapErr` takes a `Result<T, E>` and returns a `E` when the result is an `Err`, otherwise it throws a custom object.
1244
+
1245
+ That way you can do something like:
1246
+
1247
+ ```typescript
1248
+ expect(myResult._unsafeUnwrap()).toBe(someExpectation)
1249
+ ```
1250
+
1251
+ However, do note that `Result` instances are comparable. So you don't necessarily need to unwrap them in order to assert expectations in your tests. So you could also do something like this:
1252
+
1253
+ ```typescript
1254
+ import { ok } from 'resultar'
1255
+
1256
+ // ...
1257
+
1258
+ expect(callSomeFunctionThatReturnsAResult("with", "some", "args")).toEqual(ok(someExpectation));
1259
+ ```
1260
+
1261
+ By default, the thrown value does not contain a stack trace. This is because stack trace generation [makes error messages in Jest harder to understand](https://github.com/supermacro/neverthrow/pull/215). If you want stack traces to be generated, call `_unsafeUnwrap` and / or `_unsafeUnwrapErr` with a config object:
1262
+
1263
+ ```typescript
1264
+ _unsafeUnwrapErr({
1265
+ withStackTrace: true,
1266
+ })
1267
+
1268
+ // ^ Now the error object will have a `.stack` property containing the current stack
1269
+ ```
1270
+
1271
+ ---
1272
+
1273
+ If you find this package useful, please consider [sponsoring me](https://github.com/sponsors/supermacro/) or simply [buying me a coffee](https://ko-fi.com/gdelgado)!
1274
+
1275
+ ---
1276
+
1277
+ ### License
1278
+
1279
+ The resultar project is available as open source under the terms of the [MIT license](https://github.com/inaiat/resultar/blob/master/LICENSE).