Skip to content

Commit

Permalink
Update error handling in try
Browse files Browse the repository at this point in the history
  • Loading branch information
bkiac committed Nov 3, 2023
1 parent 6016137 commit c99350d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/error/result_error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class StdError extends ResultError {
readonly tag = "StdError"
}

export type ErrorHandler<E extends ResultError = StdError> = (error: StdError) => E
export type ErrorHandler<E extends ResultError = StdError> = (error: unknown) => E

export function toStdError(error: unknown): StdError {
if (error instanceof Panic) {
Expand Down
12 changes: 10 additions & 2 deletions src/helpers/try.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import {Panic} from "../error/panic"
import {type ErrorHandler, type ResultError, type StdError, toStdError} from "../error/result_error"
import {Err} from "../result/err"
import type {Result} from "../result/interface"
import {Ok} from "../result/ok"
import {PromiseResult} from "../result/promise"

function handlePanic(error: unknown) {
if (error instanceof Panic) {
throw error
}
return error
}

// Couldn't figure out how to overload these functions without a TypeScript error and making
// the error handler required if the error template param is defined.

Expand All @@ -22,7 +30,7 @@ export function tryFnWith<T, E extends ResultError>(
try {
return Ok(f())
} catch (error) {
return Err(handleError(toStdError(error)))
return Err(handleError(handlePanic(error)))
}
}

Expand All @@ -42,7 +50,7 @@ export function tryPromiseWith<T, E extends ResultError>(
return new PromiseResult<T, E>(
promise.then(
(value) => Ok(value),
(error: unknown) => Err(handleError(toStdError(error))),
(error: unknown) => Err(handleError(handlePanic(error))),
),
)
}
Expand Down

0 comments on commit c99350d

Please sign in to comment.