valueOrThrow
function valueOrThrow<T>(__namedParameters): T;Defined in: error.ts:36
Return a fallback value or throw, depending on a caller-supplied flag. Call it on the invalid path of a function that offers both a lenient and a strict mode.
throwOnInvalid: false(the default): returnsvalue.throwOnInvalid: true: throwserror. AnErrorinstance is thrown as is; a string is wrapped innew Error(error).
It does no validation of its own: with throwOnInvalid: true it always throws.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T |
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
__namedParameters |
{ error: string | Error; throwOnInvalid?: boolean; value: T; } |
__namedParameters.error |
string | Error |
__namedParameters.throwOnInvalid? |
boolean |
__namedParameters.value |
T |
Returns
Section titled “Returns”T
Examples
Section titled “Examples”A parser with a strict mode
import { valueOrThrow } from "@xtandard/lib";
function parsePort(input: string, { strict = false } = {}) { const port = Number(input); if (Number.isInteger(port) && port > 0 && port < 65536) return port; return valueOrThrow({ value: undefined, error: `Invalid port: ${input}`, throwOnInvalid: strict, });}
parsePort("8080"); // 8080parsePort("http"); // undefinedparsePort("http", { strict: true }); // throws Error("Invalid port: http")Throw your own error class
valueOrThrow({ value: null, error: new TypeError("bad input"), throwOnInvalid: true });// throws the TypeError itself