Skip to content

Commit

Permalink
Include error cause in unwrap()/expect() errors (#20)
Browse files Browse the repository at this point in the history
This is useful to get access to the "underlying" error in global
exception-handling code for example.

Feature requested in [1] and I had a question about something similar as
well[2].

[1] vultix#34
[2] vultix#48

This change depends on #17 and #19 to be merged first (then the branch will be updated to contain these changes and the build will succeed).
  • Loading branch information
jstasiak authored Mar 29, 2022
1 parent 3f43893 commit 73a700e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
10 changes: 8 additions & 2 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,17 @@ export class ErrImpl<E> implements BaseResult<never, E> {
}

expect(msg: string): never {
throw new Error(`${msg} - Error: ${toString(this.val)}\n${this._stack}`);
// The cause casting required because of the current TS definition beign overly restrictive
// (the definition says it has to be an Error while it can be anything).
// See https://github.com/microsoft/TypeScript/issues/45167
throw new Error(`${msg} - Error: ${toString(this.val)}\n${this._stack}`, { cause: this.val as any });
}

unwrap(): never {
throw new Error(`Tried to unwrap Error: ${toString(this.val)}\n${this._stack}`);
// The cause casting required because of the current TS definition beign overly restrictive
// (the definition says it has to be an Error while it can be anything).
// See https://github.com/microsoft/TypeScript/issues/45167
throw new Error(`Tried to unwrap Error: ${toString(this.val)}\n${this._stack}`, { cause: this.val as any });
}

map(_mapper: unknown): Err<E> {
Expand Down
18 changes: 14 additions & 4 deletions test/err.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,27 @@ test('else, unwrapOr', () => {
});

test('expect', () => {
expect(() => {
try {
const err = Err(true).expect('should fail!');
expect_never(err, true);
}).toThrowError('should fail!');
throw new Error('Unreachable')
}
catch (e) {
expect((e as Error).message).toMatch('should fail!')
expect((e as Error).cause).toEqual(true)
}
});

test('unwrap', () => {
expect(() => {
try {
const err = Err({ message: 'bad error' }).unwrap();
expect_never(err, true);
}).toThrowError('{"message":"bad error"}');
throw new Error('Unreachable')
}
catch (e) {
expect((e as Error).message).toMatch('{"message":"bad error"}')
expect((e as Error).cause).toEqual({ message: 'bad error' })
}
});

test('map', () => {
Expand Down

0 comments on commit 73a700e

Please sign in to comment.