Skip to content

Function: fallbackIfFails()

fallbackIfFails<T, TArgs>(target, args, fallback): T

Defined in: packages/core/src/fallbackIfFails.ts:103

fallbackIfFails

Type Parameters

T

T

TArgs

TArgs extends unknown[] = unknown[]

Parameters

target

promise or function to execute

T | (...args) => T

args

arguments to be supplied to func fuction

TArgs | () => TArgs

fallback

alternative value to be used when target throws error.

  • If fallback is a function and it raises exception, it will cause to raise an exception instead of gracefully ignoring it. A fallback of the fallback function is out of the scope of fallbackIfFails. However, the fallback function can still be wrapped inside a secondary fallbackIfFails. See the "Fallback chaining" example below.
  • If target a promise or async function, fallback can be either be a value, a promise or an async function.

IfPromiseAddValue<T> | (reason) => IfPromiseAddValue<T>

Returns

T

if func is a promise the return a promise

Examples:

Examples

Working with async functions or functions that returns a promise

typescript
import { fallbackIfFails } from '@superutils/core'

const args = ['some value', true] as const
const ensureValue = async (value: string, criteria?: boolean) => {
    if (criteria !== false && !value.trim()) throw new Error('No value. Should use fallback value')
    return value
}
// This makes sure there's always a value without having to manually write try-catch block.
const value = await fallbackIfFails(
    ensureValue,
    () => args,
    async () => 'fallback value'
)

Working synchronous function that returns value synchronously

typescript
import { fallbackIfFails } from '@superutils/core'

const args = ['some value', true] as const
const ensureValue = (value: string, criteria?: boolean) => {
    if (criteria !== false && !value.trim()) throw new Error('No value. Should use fallback value')
    return value
}
// this makes sure there's always a value without having to manually write try-catch block.
const value = fallbackIfFails(
    ensureValue,
    () => args,
    () => 'fallback value'
)

Working with function that returns value sync/async circumstantially

typescript
import { fallbackIfFails } from '@superutils/core'

const getData = (useCache = true, cacheKey = 'data-cache') => {
    if (useCache && localStorage[cacheKey]) return localStorage[cacheKey]
    return fetch('https://my.domain.com/api')
        .then(r => r.json())
        .then(data => {
		       if(cacheKey) localStorage[cacheKey] = data
            return data
        })
}
// First call: no cache, will execute fetch and return a promise
const first = await fallbackIfFails(getData, [false], {})
// Second call: cache available and will return data synchronously
const second = fallbackIfFails(getData, [true], {})
typescript
import { fallbackIfFails } from '@superutils/core'

const target = () => {
    if (new Date().getTime() > 0) throw new Error('I will raise error')
}
const fallback = () => {
    throw new Error('I will also raise an exception')
}
const value = fallbackIfFails(
    target,
    [],
	   // this function will only be invoked when
    () => fallbackIfFails(fallback, [], undefined)
)

console.log({ value }) // undefined