Skip to content

feature: add asGuardedError #21

Description

@hrajchert

This function can work well with chainP or tryCatch

It can be used to make sure an error is what we say it is. It can be implemented as following

import { UnknownError } from '@ts-task/task';

type Guard <G> = (val: any) => val is G;

export function asGuardedError<E> (guard: Guard<E>) {
    return function (val: any): E | UnknownError {
        if (guard(val)) {
            return val;
        } else {
            return new UnknownError(val);
        }
    };
}

And used like this

import * as fs from '@ts-task/fs';
import { tryCatch, asGuardedError } from '@ts-task/utils';

function isSyntaxError (error: any): error is SyntaxError {
    return error instanceof SyntaxError;
}

const asSyntaxError = asGuardedError(isSyntaxError);

export const readConfig = (path: string) =>
    fs.readFile(path).pipe(
        map(buffer => buffer.toString()),
        tryCatch(JSON.parse, asSyntaxError),
    );

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions