Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mapError exception handling #130

Merged
merged 1 commit into from
Feb 14, 2024
Merged
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
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')
})
})

Loading