Skip to content

Usage

Try and TryAsync

These functions are what you use to wrap your functions that may or may not throw an exception. You can also use it to wrap any function where you want to create a little bit more security.

import { Try } from "@/modules/utility/result"
const parsed = Try(JSON.parse)("some data")

As the name suggests TryAsync is for wrapping any async functions, which allows you to await the result.

As you can see, Try & TryAsync returns a function that you use to invoke your method. This means that you could create “safe” variants of any of your functions and enforce the exception handling for anyone who uses your functions.

import { TryAsync } from "@/modules/utility/result"
export const $getUser = TryAsync(async () => {
// ... implementation
})

Gotcha

There are some rare cases where simply passing the function can result it in “losing context”, in those cases you can pass in an anonymous function into the Try or TryAsync methods. An example, the response.json() method when fetching data.

const response = await fetch('...')
const json = await TryAsync(() => response.json())()

I haven’t run into many of these cases, but you’ll know pretty quickly when this happens. Additionally, a lot of times you have abstracted away calling fetch directly with a custom client.

Ok and Err

The Try and TryAsync methods returns a Result<T> type. Which is a union of T and Error, where T is your function return type. The Ok and Err methods will check and narrow your type down to either T or Error.

import { TryAsync, Err } from "@/modules/utility/result"
const result = await TryAsync(someFn)()
if (Err(result)) {
// `result` is of type `Error`
return
}
// `result` is of type `T`

UnwrapOr

This method will attempt to “unwrap” the value into T however, if it encounters an Error it will return the default value. This is useful for when you don’t care about the error and can happily proceed with a default value. An example might be some feature flags or validating environment variables.

import { Try, UnwrapOr } from "@/modules/utility/result"
const SOME_ENV = UnwrapOr(Try(env)("SOME_ENV"), undefined)

In the example above, if the env function fails (lets say if the SOME_ENV isn’t found in the process.env), then we can just default it to undefined instead of handling the error or throwing and killing your application.