Skip to content

Commit 2185c0d

Browse files
committed
Add custom error message to expect on non result values
1 parent 3f2d05c commit 2185c0d

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/index.test.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,9 @@ describe.each([
417417
expect.fail("Should have thrown");
418418
} catch (e) {
419419
expect(e).toStrictEqual(
420-
new Error(`Unwrapping a non-result value: ${string}`)
420+
new Error(
421+
`Custom error message: Expecting result from a non-result value: ${string}`
422+
)
421423
);
422424
}
423425
});

src/index.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,17 @@ export function unwrap<T>(result: Result<T, never>): T;
195195
* @returns The underlying value of an ok result
196196
*/
197197
export function unwrap<T, E = unknown>(result: Result<T, E>): T {
198-
return expect<T>(result, "Unwrapping an error result");
198+
if (!isResult(result)) {
199+
throw new Error(`Unwrapping a non-result value: ${JSON.stringify(result)}`);
200+
}
201+
202+
if (isErr(result)) {
203+
throw new Error(
204+
`Unwrapping an error result: ${JSON.stringify(result.Err)}`
205+
);
206+
}
207+
208+
return result.Ok;
199209
}
200210

201211
/**
@@ -231,7 +241,9 @@ export function expect<T>(result: Result<T, unknown>, message: string): T;
231241
*/
232242
export function expect<T>(result: Result<T, unknown>, message: string): T {
233243
if (!isResult(result)) {
234-
throw new Error(`Unwrapping a non-result value: ${JSON.stringify(result)}`);
244+
throw new Error(
245+
`${message}: Expecting result from a non-result value: ${JSON.stringify(result)}`
246+
);
235247
}
236248

237249
if (isErr(result)) {

0 commit comments

Comments
 (0)