Skip to content

Commit

Permalink
Changed tryCatch API
Browse files Browse the repository at this point in the history
  • Loading branch information
mantoci committed Jun 17, 2022
1 parent 246df49 commit 0bb2999
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
18 changes: 5 additions & 13 deletions src/either/either.utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,17 @@ describe('Either utils', () => {
describe('tryCatch', () => {
describe('when callback runs successfully', () => {
it('runs safely', () => {
expect(
tryCatch(
() => 5,
() => Error('some error')
)
).toBeRight(5)
expect(tryCatch(() => 5)).toBeRight(5)
})
})

describe('when callback throws', () => {
it('runs safely', () => {
expect(
tryCatch(
() => {
throw new Error('some error')
},
(it) => ({ data: it.message })
)
).toBeLeft({ data: 'some error' })
tryCatch(() => {
throw new Error('some error')
})
).toBeLeft(Error('some error'))
})
})
})
Expand Down
10 changes: 5 additions & 5 deletions src/either/either.utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { leftOf, rightOf } from './either'
import { left, right } from './either'
import { Either, Left, Right } from '../types'

export const tryCatch = <E, A>(tryFn: () => A | Either<E, A>, catchFn: (e: any) => E | Either<E, A>): Either<E, A> => {
export const tryCatch = <A>(tryFn: () => A): Either<unknown, A> => {
try {
return rightOf(tryFn())
} catch (e: any) {
return leftOf(catchFn(e))
return right(tryFn())
} catch (e) {
return left(e)
}
}

Expand Down

0 comments on commit 0bb2999

Please sign in to comment.