try-ts
v1.0.4
Published
A opt in TypeScript Result type implementation for elegant error handling
Downloads
15
Maintainers
Readme
Try TS
A Opt-in TypeScript Result type implementation for elegant error handling with full type safety.
Installation
Features
- Opt-in Type-safe error handling
- Full TypeScript support
- Zero dependencies
Usage
Basic Usage
import { ResultError, withResult } from 'try-ts';
// Define a custom error type
type UserError = "USER_NOT_FOUND";
// Wrap the async function with `withResult` to enable type-safe error handling
const getUser = withResult<UserError>()(async (id: string) => {
// Fetch user data
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
const data = await response.json() as { id: string; name: string };
// Check for 404 error and return a ResultError with custom error code
if (response.status === 404) {
return new ResultError("USER_NOT_FOUND", `User with id ${id} not found`); // `ResultError<UserError>`
}
return data;
});
async function main() {
// Fetch user info; `user` is of type `{ id: string; name: string }`
const user = await getUser("not-found");
console.log(user.name);
// `userResult` is of type `Result<{ id: string; name: string }, ResultError<UserError>>`
const userResult = await getUser("not-found").try();
// Check if the operation was successful and handle accordingly
if (userResult.isOk) {
// `userResult.value` is `{ id: string; name: string }`
console.log("User found:", userResult.value);
} else {
// Handle different error cases based on error code
switch (userResult.error.code) {
case "USER_NOT_FOUND":
console.error("User not found...");
break;
default:
console.error("An unexpected error occurred");
break;
}
}
}
main();
