@rimbu/common
Version:
Common types and objects used in many other Rimbu packages
47 lines (42 loc) • 1.23 kB
text/typescript
/**
* Throws an `ErrBase.ForcedError` error when called.
* @example
* ```ts
* const emptyMap = HashMap.empty<number, string>()
* emptyMap.get(5, Err);
* // throws: ErrBase.ForcedError(message: 'Err: Forced to throw error')
* ```
*/
export function Err(): never {
return ErrBase.msg('Err: Forced to throw error')();
}
export namespace ErrBase {
/**
* A custom error instance.
*/
export abstract class CustomError {
constructor(readonly message: string) {}
get name(): string {
return this.constructor.name;
}
}
/**
* Error type that is thrown by `Err` and the functions returned by `ErrBase.msg`.
*/
export class ForcedError extends CustomError {}
/**
* Returns a function that, when called, throws an `Err.ForcedError` with the given `message` string.
* @param message - the message to put in the `Err.ForcedError` instance.
* @example
* ```ts
* const emptyMap = HashMap.empty<number, string>()
* emptyMap.get(5, ErrBase.msg('not found'));
* // throws: ErrBase.ForcedError(message: 'not found')
* ```
*/
export function msg(message: string): () => never {
return function (): never {
throw new ErrBase.ForcedError(message);
};
}
}