sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.18k stars 167 forks source link

Feature request: Ensure that Error objects are returned by `tryit` #324

Open stefaanv opened 1 year ago

stefaanv commented 1 year ago

Right now, tryit can return any type. Ensuring that Error objects are returned avoids having to check the error type each and every time. That is especially usefull in typescript. I typically use the below code, there are alternatives circulating on the internet. I always wrap the radash tryit function right now but that's boilerplate and I believe erveryone would benefit from this.

export function ensureError<E = Error>(error: unknown): E {
  if (error instanceof Error) return error as E
  if (['boolean', 'number', 'string'].includes(typeof error))
    return new Error((error as boolean | number | string).toString()) as E
  return new Error(JSON.stringify(error)) as E
}