UNPKG

@konker.dev/tiny-error-fp

Version:

A configurable error for Typescript projects based on Effect-ts

57 lines 2.79 kB
/* eslint-disable fp/no-class,fp/no-unused-expression,fp/no-mutation,fp/no-this,fp/no-nil */ import { Either, identity, pipe, Schema } from 'effect'; import { TINY_ERROR_DEFAULT_CODE_TAG, TINY_ERROR_DEFAULT_INTERNAL, TINY_ERROR_DEFAULT_STATUS_CODE, TINY_ERROR_UNKNOWN_STRING, } from './consts.js'; import { getStackTraceString, hasErrorMessage, hasTag, isError } from './lib.js'; // -------------------------------------------------------------------------- export class TinyErrorC extends Error { _tag; statusCode; codeTag; internal; constructor(tag, name, message, statusCode, codeTag, cause, internal, stack) { super(); this._tag = tag; this.name = name; this.message = message; this.statusCode = statusCode; this.codeTag = codeTag ?? TINY_ERROR_DEFAULT_CODE_TAG; this.cause = cause ?? TINY_ERROR_UNKNOWN_STRING(); this.internal = internal ?? TINY_ERROR_DEFAULT_INTERNAL; this.stack = stack ?? super.stack ?? getStackTraceString(); } toObject() { return { _tag: this._tag, name: this.name, message: this.message, statusCode: this.statusCode, codeTag: this.codeTag, cause: this.cause, internal: this.internal, stack: this.stack, }; } } // -------------------------------------------------------------------------- export const TinyError = (tag, defaultStatusCode = TINY_ERROR_DEFAULT_STATUS_CODE, defaultName = tag, defaultMessage = tag) => (name, message, statusCode, codeTag, cause, internal, stack) => { return new TinyErrorC(tag, name ?? defaultName, message ?? defaultMessage, statusCode ?? defaultStatusCode, codeTag, cause, internal, stack); }; // -------------------------------------------------------------------------- export const isTinyError = (tag) => (x) => hasTag(tag)(x) && isError(x); // -------------------------------------------------------------------------- export const toTinyError = (tag, ctor) => (x, name, message, statusCode, codeTag, cause, internal) => { if (isTinyError(tag)(x)) return x; if (isError(x)) { return ctor(name ?? x.name, message ?? x.message, statusCode, codeTag, cause ?? x, internal, x.stack); } if (hasErrorMessage(x)) { return ctor(name, message ?? x.message, statusCode, codeTag, cause ?? x, internal); } if (typeof x === 'string') { return ctor(name, message ?? x, statusCode, codeTag, cause ?? x, internal); } return ctor(name, message ?? pipe(x, Schema.encodeEither(Schema.parseJson()), Either.match({ onLeft: TINY_ERROR_UNKNOWN_STRING, onRight: identity })), statusCode, codeTag, cause ?? x, internal); }; //# sourceMappingURL=index.js.map