Skip to content

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): returns value.
  • throwOnInvalid: true: throws error. An Error instance is thrown as is; a string is wrapped in new Error(error).

It does no validation of its own: with throwOnInvalid: true it always throws.

Type Parameter
T
Parameter Type
__namedParameters { error: string | Error; throwOnInvalid?: boolean; value: T; }
__namedParameters.error string | Error
__namedParameters.throwOnInvalid? boolean
__namedParameters.value T

T

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"); // 8080
parsePort("http"); // undefined
parsePort("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