Motivation

Why ?

Error management in JS/TS is difficult, to overcome this we created our own structure inspired by Rust's error management.

But that's not enough. Managing a bunch of packages and their errors becomes very difficult at some point. This is exactly why we are coming to a point where we cannot trust js stack trace. We believe that in projects where many people work, it will be much more beneficial for us to make small performance sacrifices in order to make the code easier to debug.

The solution we implemented to achieve this is to create a custom error type like this (this is an oversimplified version of the codebase)

There must be a causal chain for errors.

class ProjectError extends Error {
  constructor(
    public name: string,
    public message: string,
    public cause: string[] = [],
    public data: BlobType[] = [],
    public timestamp: number = Date.now()
  ) {
    super()
  }

  // ...
}

const error = new ProjectError("?test", "this is a test error", ["example-function", "app"])

Now we can combine it with neverthrow to achieve the desired result.

import { wrap, unwrap, ProjectError } from "@sirutils/core"

const getUser = wrap((name?: string) => {
    if(name === "alice") {
        return ProjectError.create("?unexpected", "name alice is not allowed").throw()
    }

    return [
        // some data...
    ]
}, "?get-user")

// getUser = (name?: string) => Result<any[], ProjectError>

const result = getUser("alice")
// result = Result<any[], ProjectError>

if(result.isErr()) {
    console.log(result.error)
    /*
    ProjectError {
        name: "unexpected", <-- code
        message: "name alice is not allowed" <-- message
        cause: [ 
            "?get-user"
        ] <-- error chain
    }
    */

   process.exit() // for truthiness narrowing *1
}

console.log(result.value) // <-- value is guaranteed because of narrowing

*1 -> https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing

As seen in the example, errors reached us with the cause chain and correct types.