Protects a function from throwing errors by returning a Result object.
Result
success
data
error
const okFn = () => 'ok';const errorFn = () => { throw new Error('error') };const okResult = protect(okFn)(); // { success: true, data: 'ok' }const errorResult = protect(errorFn)(); // { success: false, error: Error('error') } Copy
const okFn = () => 'ok';const errorFn = () => { throw new Error('error') };const okResult = protect(okFn)(); // { success: true, data: 'ok' }const errorResult = protect(errorFn)(); // { success: false, error: Error('error') }
Rest
Protects a function from throwing errors by returning a
Result
object.success
property indicates whether the function succeeded or not.data
property contains the return value of the function if it succeeded.error
property contains the error thrown by the function if it failed.data
anderror
properties will contain the resolved value and the rejected error respectively.Example