tryError Documentation
Basic Examples
Common patterns and real-world examples using tryError
JSON Parsing
One of the most common use cases for tryError is safe JSON parsing:
Safe JSON Parsing with Fallbackstypescript
1import { trySync, isTryError } from '@try-error/core';
2
3function parseUserConfig(jsonString: string) {
4 const result = trySync(() => JSON.parse(jsonString));
5
6 if (isTryError(result)) {
7 console.error('Invalid JSON configuration:', result.message);
8 return {
9 theme: 'light',
10 language: 'en',
11 notifications: true
12 }; // Return default config
13 }
14
15 return result;
16}
17
18// Usage
19const configJson = '{"theme": "dark", "language": "es"}';
20const config = parseUserConfig(configJson);
21console.log(config.theme); // "dark"
22
23const invalidJson = '{"theme": "dark", "language":}'; // Invalid JSON
24const fallbackConfig = parseUserConfig(invalidJson);
25console.log(fallbackConfig.theme); // "light" (default)
API Calls
Handle network requests with proper error handling:
API Calls with Error Handlingtypescript
1import { tryAsync, isTryError } from '@try-error/core';
2
3async function fetchUserProfile(userId: string) {
4 // Fetch user data
5 const userResponse = await tryAsync(() =>
6 fetch(`/api/users/${userId}`)
7 );
8
9 if (isTryError(userResponse)) {
10 return {
11 error: 'Network error',
12 message: userResponse.message,
13 user: null
14 };
15 }
16
17 // Check if response is ok
18 if (!userResponse.ok) {
19 return {
20 error: 'API error',
21 message: `HTTP ${userResponse.status}: ${userResponse.statusText}`,
22 user: null
23 };
24 }
25
26 // Parse JSON response
27 const userData = await tryAsync(() => userResponse.json());
28
29 if (isTryError(userData)) {
30 return {
31 error: 'Parse error',
32 message: 'Invalid JSON response',
33 user: null
34 };
35 }
36
37 return {
38 error: null,
39 message: 'Success',
40 user: userData
41 };
42}
43
44// Usage
45const profile = await fetchUserProfile('123');
46if (profile.error) {
47 console.error(`Failed to load profile: ${profile.message}`);
48} else {
49 console.log('User loaded:', profile.user.name);
50}
File Operations (Node.js)
Safe file reading and writing operations:
File Operations with Error Handlingtypescript
1import { trySync, tryAsync, isTryError } from '@try-error/core';
2import fs from 'fs';
3
4// Synchronous file reading
5function readConfigFile(path: string) {
6 const result = trySync(() => fs.readFileSync(path, 'utf8'));
7
8 if (isTryError(result)) {
9 console.error(`Failed to read config file: ${result.message}`);
10 return null;
11 }
12
13 // Parse the JSON content
14 const parseResult = trySync(() => JSON.parse(result));
15
16 if (isTryError(parseResult)) {
17 console.error(`Invalid JSON in config file: ${parseResult.message}`);
18 return null;
19 }
20
21 return parseResult;
22}
23
24// Asynchronous file operations
25async function saveUserData(userId: string, data: any) {
26 const jsonString = JSON.stringify(data, null, 2);
27 const filePath = `./data/users/${userId}.json`;
28
29 const result = await tryAsync(() =>
30 fs.promises.writeFile(filePath, jsonString, 'utf8')
31 );
32
33 if (isTryError(result)) {
34 console.error(`Failed to save user data: ${result.message}`);
35 return false;
36 }
37
38 console.log(`User data saved to ${filePath}`);
39 return true;
40}
41
42// Usage
43const config = readConfigFile('./config.json');
44if (config) {
45 console.log('Config loaded:', config);
46}
47
48const saved = await saveUserData('123', { name: 'John', age: 30 });
49if (!saved) {
50 console.error('Failed to save user data');
51}
Form Validation
Validate user input with detailed error reporting:
Form Validation with Error Aggregationtypescript
1import { trySync, isTryError } from '@try-error/core';
2
3interface UserForm {
4 email: string;
5 age: string;
6 password: string;
7}
8
9function validateEmail(email: string) {
10 const result = trySync(() => {
11 if (!email) throw new Error('Email is required');
12 if (!email.includes('@')) throw new Error('Invalid email format');
13 if (email.length < 5) throw new Error('Email too short');
14 return email.toLowerCase();
15 });
16 return result;
17}
18
19function validateAge(ageString: string) {
20 const result = trySync(() => {
21 if (!ageString) throw new Error('Age is required');
22 const age = parseInt(ageString, 10);
23 if (isNaN(age)) throw new Error('Age must be a number');
24 if (age < 13) throw new Error('Must be at least 13 years old');
25 if (age > 120) throw new Error('Invalid age');
26 return age;
27 });
28 return result;
29}
30
31function validatePassword(password: string) {
32 const result = trySync(() => {
33 if (!password) throw new Error('Password is required');
34 if (password.length < 8) throw new Error('Password must be at least 8 characters');
35 if (!/[A-Z]/.test(password)) throw new Error('Password must contain uppercase letter');
36 if (!/[0-9]/.test(password)) throw new Error('Password must contain a number');
37 return password;
38 });
39 return result;
40}
41
42function validateUserForm(form: UserForm) {
43 const errors: string[] = [];
44 const validatedData: any = {};
45
46 // Validate email
47 const emailResult = validateEmail(form.email);
48 if (isTryError(emailResult)) {
49 errors.push(`Email: ${emailResult.message}`);
50 } else {
51 validatedData.email = emailResult;
52 }
53
54 // Validate age
55 const ageResult = validateAge(form.age);
56 if (isTryError(ageResult)) {
57 errors.push(`Age: ${ageResult.message}`);
58 } else {
59 validatedData.age = ageResult;
60 }
61
62 // Validate password
63 const passwordResult = validatePassword(form.password);
64 if (isTryError(passwordResult)) {
65 errors.push(`Password: ${passwordResult.message}`);
66 } else {
67 validatedData.password = passwordResult;
68 }
69
70 return {
71 valid: errors.length === 0,
72 errors,
73 data: validatedData
74 };
75}
76
77// Usage
78const formData = {
79 email: 'user@example.com',
80 age: '25',
81 password: 'SecurePass123'
82};
83
84const validation = validateUserForm(formData);
85if (validation.valid) {
86 console.log('Form is valid:', validation.data);
87} else {
88 console.error('Validation errors:', validation.errors);
89}
Database Operations
Handle database operations with proper error handling:
Database Repository Patterntypescript
1import { tryAsync, isTryError } from '@try-error/core';
2
3class UserRepository {
4 constructor(private db: any) {}
5
6 async createUser(userData: any) {
7 const result = await tryAsync(() =>
8 this.db.users.create(userData)
9 );
10
11 if (isTryError(result)) {
12 console.error('Failed to create user:', result.message);
13 return { success: false, error: result.message };
14 }
15
16 return { success: true, user: result };
17 }
18
19 async findUserById(id: string) {
20 const result = await tryAsync(() =>
21 this.db.users.findById(id)
22 );
23
24 if (isTryError(result)) {
25 console.error('Failed to find user:', result.message);
26 return null;
27 }
28
29 return result;
30 }
31
32 async updateUser(id: string, updates: any) {
33 const result = await tryAsync(() =>
34 this.db.users.update(id, updates)
35 );
36
37 if (isTryError(result)) {
38 console.error('Failed to update user:', result.message);
39 return { success: false, error: result.message };
40 }
41
42 return { success: true, user: result };
43 }
44
45 async deleteUser(id: string) {
46 const result = await tryAsync(() =>
47 this.db.users.delete(id)
48 );
49
50 if (isTryError(result)) {
51 console.error('Failed to delete user:', result.message);
52 return { success: false, error: result.message };
53 }
54
55 return { success: true };
56 }
57}
58
59// Usage
60const userRepo = new UserRepository(database);
61
62// Create user
63const createResult = await userRepo.createUser({
64 name: 'John Doe',
65 email: 'john@example.com'
66});
67
68if (createResult.success) {
69 console.log('User created:', createResult.user);
70} else {
71 console.error('Failed to create user:', createResult.error);
72}
73
74// Find user
75const user = await userRepo.findUserById('123');
76if (user) {
77 console.log('User found:', user.name);
78} else {
79 console.log('User not found');
80}
Configuration Loading
Load and validate application configuration with fallbacks:
Configuration Loading with Fallbackstypescript
1import { trySync, isTryError } from '@try-error/core';
2
3interface AppConfig {
4 port: number;
5 database: {
6 host: string;
7 port: number;
8 name: string;
9 };
10 features: {
11 enableLogging: boolean;
12 enableMetrics: boolean;
13 };
14}
15
16const defaultConfig: AppConfig = {
17 port: 3000,
18 database: {
19 host: 'localhost',
20 port: 5432,
21 name: 'myapp'
22 },
23 features: {
24 enableLogging: true,
25 enableMetrics: false
26 }
27};
28
29function loadConfig(): AppConfig {
30 // Try to load from environment variables
31 const envResult = trySync(() => {
32 const port = process.env.PORT;
33 const dbHost = process.env.DB_HOST;
34 const dbPort = process.env.DB_PORT;
35
36 if (!port || !dbHost || !dbPort) {
37 throw new Error('Missing required environment variables');
38 }
39
40 return {
41 port: parseInt(port, 10),
42 database: {
43 host: dbHost,
44 port: parseInt(dbPort, 10),
45 name: process.env.DB_NAME || defaultConfig.database.name
46 },
47 features: {
48 enableLogging: process.env.ENABLE_LOGGING === 'true',
49 enableMetrics: process.env.ENABLE_METRICS === 'true'
50 }
51 };
52 });
53
54 if (!isTryError(envResult)) {
55 console.log('Configuration loaded from environment variables');
56 return envResult;
57 }
58
59 // Try to load from config file
60 const fileResult = trySync(() => {
61 const fs = require('fs');
62 const configFile = fs.readFileSync('./config.json', 'utf8');
63 return JSON.parse(configFile);
64 });
65
66 if (!isTryError(fileResult)) {
67 console.log('Configuration loaded from config.json');
68 return { ...defaultConfig, ...fileResult };
69 }
70
71 // Fall back to default configuration
72 console.warn('Using default configuration');
73 return defaultConfig;
74}
75
76// Usage
77const config = loadConfig();
78console.log(`Server will run on port ${config.port}`);
79console.log(`Database: ${config.database.host}:${config.database.port}`);