Skip to content

Commit

Permalink
Merge pull request #130 from seasonedcc/fix-map-error-error-case
Browse files Browse the repository at this point in the history
Fix mapError exception handling
  • Loading branch information
diogob authored Feb 14, 2024
2 parents 51bccdb + b0e0f79 commit cc23e53
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/composable/composable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function pipe<T extends [Composable, ...Composable[]]>(
//@ts-ignore pipe uses exactly he same generic input type as sequence
// I don't understand what is the issue here but ignoring the errors
// is safe and much nicer than a bunch of casts to any
const res = (await sequence(...fns)(...args))
const res = await sequence(...fns)(...args)
return !res.success ? error(res.errors) : success(res.data.at(-1))
}) as PipeReturn<T>
}
Expand Down Expand Up @@ -204,7 +204,13 @@ function mapError<T extends Composable, R>(
) {
return (async (...args) => {
const res = await fn(...args)
return !res.success ? error(mapper(res).errors) : success(res.data)
if (res.success) return success(res.data)
const mapped = await composable(mapper)(res)
if (mapped.success) {
return error(mapped.data.errors)
} else {
return error(mapped.errors)
}
}) as T
}

Expand Down
30 changes: 30 additions & 0 deletions src/composable/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,21 @@ describe('map', () => {
assertEquals(res.success, false)
assertEquals(res.errors![0].message, 'a is 1')
})

it('fails when mapper fail', async () => {
const fn = map(add, () => {
throw new Error('Mapper also has problems')
})
const res = await fn(1, 2)

type _FN = Expect<
Equal<typeof fn, Composable<(a: number, b: number) => never>>
>
type _R = Expect<Equal<typeof res, Result<never>>>

assertEquals(res.success, false)
assertEquals(res.errors![0].message, 'Mapper also has problems')
})
})

const cleanError = (err: ErrorWithMessage) => ({
Expand All @@ -351,5 +366,20 @@ describe('mapError', () => {
assertEquals(res.success, false)
assertEquals(res.errors![0].message, 'a is 1!!!')
})

it('fails when mapper fail', async () => {
const fn = mapError(faultyAdd, () => {
throw new Error('Mapper also has problems')
})
const res = await fn(1, 2)

type _FN = Expect<
Equal<typeof fn, Composable<(a: number, b: number) => number>>
>
type _R = Expect<Equal<typeof res, Result<number>>>

assertEquals(res.success, false)
assertEquals(res.errors![0].message, 'Mapper also has problems')
})
})

0 comments on commit cc23e53

Please sign in to comment.