![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
@tszen/trycatch
Advanced tools
Haven’t read the blog post yet? You can find it here for a deep dive into the design and reasoning behind this project. Here's a quick snapshot to get you started:
JavaScript's error management design lags behind modern languages like Rust, Zig, and Go. Language design is hard, and most proposals to the ECMAScript or TypeScript committees are either rejected or move through an extremely slow iteration process.
Most libraries and user-land solutions in this area introduce abstractions that fall into the red/blue function problem, requiring full codebase adoption and resulting in technology lock-in.
The goal of this project is to push the boundaries of error handling in JavaScript, prioritizing conventions over abstractions and leveraging native constructs to their fullest potential. We provide a minimal set of utilities to enhance developer experience, with the hope of inspiring future language improvements and the adoption of these conventions as first-class citizens in JavaScript.
This project aims to enhance JavaScript's try/catch model for error handling by drawing inspiration from modern languages like Rust, Zig, and Go. The focus is on:
It's not enough to develop a library; the real goal is to build valid solutions that can inspire new standards in the language. Language design requires careful consideration, which is why we've defined core principles to ensure everything aligns with this broader vision:
The core of the convention relies on the concept of task. A task is any function that can either succeed or fail.
function task() {
if (condition) {
throw new Error("failed");
}
return "value";
}
We distinguish between expected errors and unexpected errors — those we can anticipate, handle, and recover from — and unexpected errors, which we can't easily predict or recover from. Unexpected errors are indicated with the throw
keyword, while expected errors are returned using the return
keyword.
function task() {
if (condition) {
// return instead of throwing.
return new Error("failed");
}
return "value";
}
Expected errors are part of the return value of the task. TypeScript's language server provides strong guidance when consuming these return values, which we now refer to as results.
const result: string | Error = task();
// Handle the error.
if (result instanceof Error) {
return;
}
result;
// ?^ result: string
Managing multiple errors becomes reliable with TypeScript’s type checker, which guides the process through autocompletion and catches mistakes at compile time.
function task() {
if (condition1) return new CustomError1();
if (condition2) return new CustomError2();
return "value";
}
// In another file...
const result = task();
if (result instanceof CustomError1) {
// Handle CustomError1.
} else if (result instanceof CustomError2) {
// Handle CustomError2.
}
Since this approach works with plain JavaScript, you can seamlessly integrate existing libraries like ts-pattern for more advanced pattern matching.
import { match } from "ts-pattern";
match(result)
.with(P.instanceOf(CustomError1), () => {
/* Handle CustomError1 */
})
.with(P.instanceOf(CustomError2), () => {
/* Handle CustomError2 */
})
.otherwise(() => {
/* Handle success case */
});
You can progressively enhance your codebase by wrapping third-party methods in tasks. The $trycatch utility further enhances this process by eliminating the need for try/catch blocks.
async function $fetch(input: string, init?: RequestInit) {
try {
// Make the request.
const response = await fetch(input, init);
// Return the response if it's OK, otherwise an error.
return response.ok ? response : new ResponseError(response);
} catch (error) {
// ?^ DOMException | TypeError | SyntaxError.
// Any cause from request abortion to a network error.
return new RequestError(error);
}
}
Composition is also possible, allowing tasks to be chained together while handling expected errors. The $macro utility simplifies this process by managing the flow of expected errors across multiple tasks.
function task() {
// Compute the result and exclude the error.
const result1: number | Error1 = task1();
if (result1 instanceof Error1) return result1;
// Compute the result and exclude the error.
const result2: number | Error2 = task2();
if (result2 instanceof Error2) return result2;
const result = result1 + result2;
}
To enhance the usage of these conventions, this library provides two utilities.
npm install @tszen/trycatch
$macro
This utility provides access to the successful result of a task and automatically propagates any errors to the caller. It enables task composition in a concise and type safe way, without the need for manual error checks.
function task1(): number | Error1;
function task2(): number | Error2;
Given these task definitions, we can compute the sum of their results like so:
const result: number | Error1 | Error2 = $macro(function* ($try) {
const result1: number = yield* $try(task1());
const result2: number = yield* $try(task2());
return result1 + result2;
});
This utility draws strong inspiration from the try
operator in Zig. It’s important to note that $macro
accept tasks following our convention and returns a result adhering to the same convention. This ensures the abstraction remains confined to its intended scope, preventing it from leaking into other parts of the codebase — neither in the caller nor the callee.
$trycatch
The $trycatch
utility allows you to handle unexpected errors in a clean, structured way by removing the need for traditional try/catch blocks.
const [result, err] = $trycatch(task);
This utility adopts a Go-style tuple approach: the first element represents the task’s result, and the second contains any unexpected error. By leveraging TypeScript’s type system, we ensure that the result remains unknown
until the error is explicitly checked and handled, preventing the accidental use of the result when an error is present.
const [result, err] = $trycatch(() => "succeed!");
// ?^ result: unknown
// ?^ err: Error | null
if (err !== null) {
return;
}
result;
// ?^ result: string
JavaScript's dynamic nature means that anything can be thrown. To handle this, we encapsulate thrown values in an Error
object and expose the original value through Error.cause
.
The utility also extends to asynchronous tasks and promises.
// Async functions.
const [result, err] = await $trycatch(async () => { ... });
// Or Promises.
const [result, err] = await $trycatch(new Promise(...));
Here is a list of known limitations:
$trycatch
must be passed functions to be executed, rather than their results. While this isn't as seamless as a language feature would behave, it’s a limitation due to the constraints of JavaScript syntax. However, $macro
and $try
do not share this issue.unknown
or any
, as these types will obscure the expected error types in the result. You can work around this by wrapping the return value in an object like { value }
.TypeError | RangeError
will be type reduced to TypeError
. This is a limitation of the TypeScript errors typings and can be addressed by relying on custom errors and wrapping native ones when needed.Copyright © 2024 tszen • MIT license.
FAQs
Unknown package
The npm package @tszen/trycatch receives a total of 2 weekly downloads. As such, @tszen/trycatch popularity was classified as not popular.
We found that @tszen/trycatch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.