try-error Documentation
Quick Start
Learn the essentials of try-error with practical examples
Synchronous Operations
Use trySync
for operations that might throw:
Synchronous Examplestypescript
import { trySync, isTryError } from 'try-error';
// JSON parsing
const parseResult = trySync(() => JSON.parse(jsonString));
if (isTryError(parseResult)) {
console.error('Invalid JSON:', parseResult.message);
return null;
}
console.log('Parsed:', parseResult);
// File operations (Node.js)
const fileResult = trySync(() => fs.readFileSync('config.json', 'utf8'));
if (isTryError(fileResult)) {
console.error('File read failed:', fileResult.message);
return defaultConfig;
}
return JSON.parse(fileResult);
Asynchronous Operations
Use tryAsync
for async operations:
Async Examplestypescript
import { tryAsync, isTryError } from 'try-error';
// API calls
const fetchUser = async (id: string) => {
const result = await tryAsync(() => fetch(`/api/users/${id}`));
if (isTryError(result)) {
console.error('Fetch failed:', result.message);
return null;
}
const jsonResult = await tryAsync(() => result.json());
if (isTryError(jsonResult)) {
console.error('JSON parse failed:', jsonResult.message);
return null;
}
return jsonResult;
};
// Database operations
const saveUser = async (user: User) => {
const result = await tryAsync(() => db.users.create(user));
if (isTryError(result)) {
console.error('Save failed:', result.message);
throw new Error('Failed to save user');
}
return result;
};
Common Patterns
Early Returns
Early Return Patterntypescript
function processData(input: string) {
const parseResult = trySync(() => JSON.parse(input));
if (isTryError(parseResult)) {
return { error: 'Invalid JSON', data: null };
}
const validateResult = trySync(() => validateSchema(parseResult));
if (isTryError(validateResult)) {
return { error: 'Validation failed', data: null };
}
return { error: null, data: validateResult };
}
Default Values
Default Values Patterntypescript
function getConfig() {
const result = trySync(() => JSON.parse(configString));
return isTryError(result) ? defaultConfig : result;
}
// Or with async
async function getUserPreferences(userId: string) {
const result = await tryAsync(() => fetchPreferences(userId));
return isTryError(result) ? defaultPreferences : result;
}
Error Aggregation
Error Aggregation Patterntypescript
async function validateForm(data: FormData) {
const errors: string[] = [];
const emailResult = trySync(() => validateEmail(data.email));
if (isTryError(emailResult)) {
errors.push(`Email: ${emailResult.message}`);
}
const phoneResult = trySync(() => validatePhone(data.phone));
if (isTryError(phoneResult)) {
errors.push(`Phone: ${phoneResult.message}`);
}
return errors.length > 0 ? { valid: false, errors } : { valid: true, errors: [] };
}
Type Safety
try-error provides full TypeScript support with intelligent type inference:
Type Safety Examplestypescript
1// Return type is automatically inferred
2const result = trySync(() => JSON.parse(jsonString));
3// result: TryResult<any, TryError>
4
5if (isTryError(result)) {
6 // result is TryError here
7 console.log(result.message, result.stack);
8} else {
9 // result is the parsed value here
10 console.log(result.someProperty);
11}
12
13// Custom types work too
14interface User {
15 id: string;
16 name: string;
17}
18
19const userResult = trySync((): User => {
20 return JSON.parse(userJson);
21});
22// userResult: TryResult<User, TryError>