Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions src/_internals/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,32 @@ const defaultErrorConfig: ErrorConfig = {
withStackTrace: false,
}

interface NeverThrowError<T, E> {
data:
| {
type: string
value: T
}
| {
type: string
value: E
}
message: string
stack: string | undefined
type ErrorData<T, E> = {
type: string
value: T
} | {
type: string
value: E
}

class NeverThrowError<T, E> extends Error {
data: ErrorData<T, E>

constructor({
data,
message,
stack,
}: {
data: ErrorData<T, E>
message: string
stack: string | undefined
}) {
super();
this.data = data;
this.message = message;
this.stack = stack;
Object.setPrototypeOf(this, new.target.prototype);
}
}

// Custom error object
Expand All @@ -35,9 +49,9 @@ export const createNeverThrowError = <T, E>(

const maybeStack = config.withStackTrace ? new Error().stack : undefined

return {
return new NeverThrowError<T, E>({
data,
message,
stack: maybeStack,
}
})
}
6 changes: 6 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ describe('Result.Ok', () => {
expect(okVal._unsafeUnwrap()).toBeUndefined()
})

it('Throws an error that is an instance of error', () => {
const okVal = ok(undefined)

expect(() => okVal._unsafeUnwrapErr()).toThrowError(Error);
});

it('Is comparable', () => {
expect(ok(42)).toEqual(ok(42))
expect(ok(42)).not.toEqual(ok(43))
Expand Down