|
1 | 1 | # @dschz/try-catch |
2 | 2 |
|
| 3 | +## 1.2.0 |
| 4 | + |
| 5 | +### Minor Changes |
| 6 | + |
| 7 | +**Refined synchronous execution support** - `tryCatch` now returns the appropriate type based on input, eliminating unnecessary `await` for synchronous functions. |
| 8 | + |
| 9 | +#### Supported Use Cases |
| 10 | + |
| 11 | +**Synchronous functions** - No `await` needed, returns `Result<T, E>` directly: |
| 12 | + |
| 13 | +```ts |
| 14 | +// Parse JSON |
| 15 | +const [err, data] = tryCatch(() => JSON.parse('{"a":1}')); |
| 16 | + |
| 17 | +// Functions that throw |
| 18 | +const [err, data] = tryCatch(() => { |
| 19 | + throw new RangeError("Out of bounds"); |
| 20 | +}); |
| 21 | + |
| 22 | +// Non-Error throws are wrapped in Error with cause |
| 23 | +const [err, data] = tryCatch(() => { |
| 24 | + throw "string error"; |
| 25 | +}); |
| 26 | +// err.message === "string error", err.cause === "string error" |
| 27 | +``` |
| 28 | + |
| 29 | +**Async functions** - Returns `Promise<Result<T, E>>`: |
| 30 | + |
| 31 | +```ts |
| 32 | +const [err, data] = await tryCatch(async () => { |
| 33 | + const res = await fetch("/api"); |
| 34 | + return res.json(); |
| 35 | +}); |
| 36 | +``` |
| 37 | + |
| 38 | +**Direct promises** - Returns `Promise<Result<T, E>>`: |
| 39 | + |
| 40 | +```ts |
| 41 | +const [err, data] = await tryCatch(fetch("/api/data")); |
| 42 | +const [err, data] = await tryCatch(Promise.resolve(42)); |
| 43 | +const [err, data] = await tryCatch(Promise.reject(new Error("fail"))); |
| 44 | +``` |
| 45 | + |
| 46 | +**Promise chains** - Returns `Promise<Result<T, E>>`: |
| 47 | + |
| 48 | +```ts |
| 49 | +const [err, data] = await tryCatch(() => fetch("/api").then((r) => r.json())); |
| 50 | +``` |
| 51 | + |
| 52 | +#### Type Exports |
| 53 | + |
| 54 | +`Result`, `Success`, and `Failure` types are now exported for use in your own type definitions: |
| 55 | + |
| 56 | +```ts |
| 57 | +import { tryCatch, Result, Success, Failure } from "@dschz/try-catch"; |
| 58 | +``` |
| 59 | + |
3 | 60 | ## 1.1.3 |
4 | 61 |
|
5 | 62 | ### Patch Changes |
|
0 commit comments