Skip to content

Commit

Permalink
Merge pull request #160 from seasonedcc/allow-from-success-to-use-any…
Browse files Browse the repository at this point in the history
…-error

We want to be able to throw arbitrary values when using fromSuccess
  • Loading branch information
diogob committed Jun 27, 2024
2 parents 7018aed + 394b3d3 commit 6b1c472
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/constructors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { mapErrors } from './combinators.ts'
import { ContextError, ErrorList, InputError } from './errors.ts'
import type { Internal } from './internal/types.ts'
import type {
Expand Down Expand Up @@ -83,10 +82,10 @@ function fromSuccess<O, P extends any[]>(
onError: (errors: Error[]) => Error[] | Promise<Error[]> = (e) => e,
): (...args: P) => Promise<O> {
return (async (...args: P) => {
const result = await mapErrors(fn, onError)(...args)
const result = await fn(...args)
if (result.success) return result.data

throw new ErrorList(result.errors)
throw new ErrorList(await onError(result.errors))
}) as (...args: P) => Promise<O>
}

Expand Down
20 changes: 20 additions & 0 deletions src/tests/constructors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from '../index.ts'
import { applySchema } from '../index.ts'
import type { Internal } from '../internal/types.ts'
import { assertInstanceOf } from 'https://deno.land/std@0.206.0/assert/assert_instance_of.ts'

const add = composable((a: number, b: number) => a + b)
const asyncAdd = (a: number, b: number) => Promise.resolve(a + b)
Expand Down Expand Up @@ -144,6 +145,25 @@ describe('fromSuccess', () => {
assertEquals(await c(), 1)
})

it('allows to throw any arbitrary value', async () => {
const a = composable(() => {
throw new Error('Some error')
})

class CustomError {}
const c = fromSuccess(a, () => {
throw new CustomError()
})
type _R = Expect<Equal<typeof c, () => Promise<never>>>

try {
await c()
throw new Error('should have thrown on the line above')
} catch (e) {
assertInstanceOf(e, CustomError)
}
})

it('allows to change the errors list', () => {
const a = composable(() => {
throw new Error('Some error')
Expand Down

0 comments on commit 6b1c472

Please sign in to comment.