Skip to content

guard

Have a function return undefined if it errors out

144 bytes

Usage

This lets you set a default value if an async function errors out.

const users = (await guard(fetchUsers)) ?? []

You can choose to guard only specific errors too

const isInvalidUserError = (err: any) => err.code === 'INVALID_ID'
const user = (await guard(fetchUser, isInvalidUserError)) ?? DEFAULT_USER