Skip to content

An idea for the safe functions #45

Description

@leonardotc

There are two issues with the safe functions as of right now:

async function blake3Safe(message) {
    try {
        return await blake3(message);
    } catch (err) {
        console.error(err);
    }
    return b4a.alloc(0); // Return an empty buffer on error
}

They produce a log, which is not a lib responsibility but rather a system responsibility and they gobled up the error which results in a semantic loss. They also return a peculiar "neutral" type which is there to keep interface structurally sound but overlaps with a valid type.

In general, a semi-better approach would be to use a higher order function that "tuple up" the result. E.g:

type SafeReturnType<T> = { error?: Error, result?: T }; // oneOf
type MakeSafe<Args extends unknown[], R> = (f: (...args: Args) => R) => (...args: Args) => SafeReturnType<R>;

Usage for this thing:

const safeBlake3 = makeSafe(blake3)
const safeSign = makeSafe(sign)

We should give the consuming end insurance that if an error was not returned then the result is valid so people could use

cont { error, result } = await blake3Safe(toHash)
if (!error) {
  const hash = result // I know this is valid 32 bytes
} else {
  this.#logger.error(`Invalid result: ${error.stack}`) // This goes to a file
}

Ideally that could be exported as a util as well to be used throughout the system.

PS: This is a sketch, there are further challenges that would come from promises etc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions