Skip to content

Commit a929652

Browse files
committed
FIX: turn values other than errors into errors for proper isError behaviour
1 parent 4339596 commit a929652

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/new.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,12 @@ export function okOr<T>(result: Result<T>, defaultValue: T) {
3838

3939
/**
4040
*
41-
* Function that takes in an async function and catches errors in it.
41+
* Function that takes in an async function and catches anything thrown in it.
4242
* Collects either the value or the error in a **_Result_** type.
4343
*
44+
* If the thrown value is an error, it is caught and returned as an error.
45+
* If the thrown value is not an error, it is turned into an error and returned.
46+
*
4447
* @param promise a promise or a called async function which returns a promise
4548
* @returns a promise containing a **_Result_** type
4649
*
@@ -50,7 +53,8 @@ export async function tryAsync<T>(promise: Promise<T>): Promise<Result<T>> {
5053
const ok = await promise;
5154
return ok;
5255
} catch (err) {
53-
return err as Error;
56+
if (err instanceof Error) return err;
57+
else return new Error(err as any);
5458
}
5559
}
5660

@@ -59,6 +63,9 @@ export async function tryAsync<T>(promise: Promise<T>): Promise<Result<T>> {
5963
* Function that takes in a callback and catches errors in it.
6064
* Collects either the value or the error in a **_Result_** type.
6165
*
66+
* If the thrown value is an error, it is caught and returned as an error.
67+
* If the thrown value is not an error, it is turned into an error and returned.
68+
*
6269
* @param callback any function that can throw
6370
* @returns a **_Result_** type
6471
*
@@ -68,6 +75,7 @@ export function trySync<T>(callback: () => T): Result<T> {
6875
const ok = callback();
6976
return ok;
7077
} catch (err) {
71-
return err as Error;
78+
if (err instanceof Error) return err;
79+
else return new Error(err as any);
7280
}
7381
}

0 commit comments

Comments
 (0)