Skip to content

Commit

Permalink
feat: add catchResult<TValue, TError>() (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickmichalina authored Nov 15, 2022
1 parent ecf09b8 commit c695fcd
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/result/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './result'
export * from './result.factory'
export * from './result.interface'
export * from './transformers/result-to-promise'
export * from './transformers/try-catch-to-result'
53 changes: 53 additions & 0 deletions src/result/transformers/try-catch-to-result.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { catchResult } from './try-catch-to-result'

describe(catchResult.name, () => {
it('should try', done => {
function someThrowable(): string {
return 'I worked!'
}

const sut = catchResult(someThrowable)

expect(sut.isOk()).toEqual(true)
expect(sut.unwrap()).toEqual('I worked!')

done()
})

it('should catch', done => {
function someThrowable(): string {
throw new Error('I failed!')
}

const sut = catchResult(someThrowable)

expect(sut.isFail()).toEqual(true)

done()
})

it('should catch with error mapping function', done => {
function someThrowable(): string {
throw new Error('I failed!')
}

class CustomError extends Error {
static fromUnknown(err: unknown): CustomError {
if (err instanceof Error) {
return new CustomError(err.message)
}
return new CustomError('new error')
}
constructor(message?: string) {
super(message)
}
}

const sut = catchResult(someThrowable, CustomError.fromUnknown)

expect(sut.isFail()).toEqual(true)
expect(sut.unwrapFail().message).toEqual('I failed!')

done()
})
})
16 changes: 16 additions & 0 deletions src/result/transformers/try-catch-to-result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { fail, ok } from '../result.factory'
import { IResult } from '../result.interface'

/**
* Ingest a try-catch throwable function so that it doesn't halt the program but instead
* returns an IResult
* @param fn a throwable function
* @returns an IResult object which wraps the execution as either fail or success
*/
export function catchResult<TValue, TError>(fn: () => TValue, errFn?: (err: unknown) => TError): IResult<TValue, TError> {
try {
return ok<TValue, TError>(fn())
} catch(err) {
return fail<TValue, TError>(errFn ? errFn(err) : err as TError)
}
}

0 comments on commit c695fcd

Please sign in to comment.