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
}
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 radashtryit
function right now but that's boilerplate and I believe erveryone would benefit from this.