@chejholloway/result-guard
v0.1.2
Published
Rust-like Result-based error handling for JS/TS, built on neverthrow. Wraps throwing functions so they return Result/ResultAsync instead, with a decorator for class-based code.
Downloads
291
Maintainers
Readme
result-guard
Wraps a throwing function so it returns a neverthrow Result/ResultAsync instead. See the project README for the full problem statement and design reasoning.
Install
npm install result-guard neverthrowUsage
import { guard } from "result-guard";
async function fetchUser(id: string) {
if (!id) throw new Error("missing id");
return { id, name: "Alice" };
}
const guardedFetch = guard(fetchUser);
const result = await guardedFetch("123");
result.match(
(user) => console.log(user),
(error) => console.error(error.kind === "error" ? error.message : "unknown failure")
);By default, guard() gives you Result<T, DefaultGuardError> — { kind: "error", name, message, cause } if the caught value was a real Error, or { kind: "unknown", cause } otherwise. Pass your own error mapper to fully replace it with typed errors specific to your domain:
type ApiError = { kind: "not-found" } | { kind: "server-error"; status: number };
const guardedFetch = guard(fetchUser, (e): ApiError =>
e instanceof NotFoundError ? { kind: "not-found" } : { kind: "server-error", status: 500 }
);Decorator
For class-based code:
class UserService {
@ResultGuard()
async fetchUser(id: string) {
if (!id) throw new Error("missing id");
return { id, name: "Alice" };
}
}Sync methods stay synchronous — guard() never forces a Promise onto a function that wasn't already async.
License
MIT
