UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

52 lines (51 loc) 2.26 kB
import type { AnyFunction, Class, ErrorDataTuple } from '../types.js'; /** * Calls a function, returns a Tuple of [error, value]. * Allows to write shorter code that avoids `try/catch`. * Useful e.g. in unit tests. * * Similar to pTry, but for sync functions. * * ERR is typed as Error, not `unknown`. While unknown would be more correct, * according to recent TypeScript, Error gives more developer convenience. * In our code we NEVER throw non-errors. * Only possibility of non-error is in the 3rd-party library code, in these cases it * can be manually cast to `unknown` for extra safety. * * @example * * const [err, v] = _try(() => someFunction()) * if (err) ...do something... * v // go ahead and use v */ export declare function _try<T, ERR extends Error = Error>(fn: () => T, errorClass?: Class<ERR>): ErrorDataTuple<T, ERR>; /** * Like _try, but for Promises. */ export declare function pTry<T, ERR extends Error = Error>(promise: Promise<T>, errorClass?: Class<ERR>): Promise<ErrorDataTuple<Awaited<T>, ERR>>; /** * Calls `fn`, expects is to throw, catches the expected error and returns. * If error was NOT thrown - throws UnexpectedPassError instead. * * If `errorClass` is passed: * 1. It automatically infers it's type * 2. It does `instanceof` check and throws if wrong Error instance was thrown. */ export declare function _expectedError<ERR = Error>(fn: AnyFunction, errorClass?: Class<ERR>): ERR; /** * Awaits passed `promise`, expects is to throw (reject), catches the expected error and returns. * If error was NOT thrown - throws UnexpectedPassError instead. * * If `errorClass` is passed: * 1. It automatically infers it's type * 2. It does `instanceof` check and throws if wrong Error instance was thrown. */ export declare function pExpectedError<ERR = Error>(promise: Promise<any>, errorClass?: Class<ERR>): Promise<ERR>; /** * Shortcut function to simplify error snapshot-matching in tests. */ export declare function pExpectedErrorString<ERR = Error>(promise: Promise<any>, errorClass?: Class<ERR>): Promise<string>; /** * Shortcut function to simplify error snapshot-matching in tests. */ export declare function _expectedErrorString<ERR = Error>(fn: AnyFunction, errorClass?: Class<ERR>): string;