tryError Documentation

Synchronous Operations

API reference for handling synchronous operations with tryError

trySync

Function Signaturetypescript
function trySync<T>(fn: () => T): TryResult<T, TryError>

Executes a synchronous function and returns either the result or a TryError if an exception is thrown.

Parameters

  • fn: () => T - The function to execute

Returns

TryResult<T, TryError> - Either the function result or a TryError

Examples

trySync Examplestypescript
1import { trySync, isTryError } from '@try-error/core';
2
3// JSON parsing
4const parseResult = trySync(() => JSON.parse('{"name": "John"}'));
5if (isTryError(parseResult)) {
6  console.error('Parse failed:', parseResult.message);
7} else {
8  console.log('Parsed:', parseResult.name); // "John"
9}
10
11// Mathematical operations
12const divideResult = trySync(() => {
13  const a = 10;
14  const b = 0;
15  if (b === 0) throw new Error('Division by zero');
16  return a / b;
17});
18
19// File operations (Node.js)
20const fileResult = trySync(() => 
21  require('fs').readFileSync('config.json', 'utf8')
22);
23
24// Type conversion
25const numberResult = trySync(() => {
26  const value = "not-a-number";
27  const num = parseInt(value, 10);
28  if (isNaN(num)) throw new Error('Invalid number');
29  return num;
30});

Type Guards

isTryError

isTryError Signaturetypescript
function isTryError(value: unknown): value is TryError

Type guard function to check if a value is a TryError. This provides type narrowing in TypeScript.

isTryError Usagetypescript
const result = trySync(() => JSON.parse(jsonString));

if (isTryError(result)) {
  // TypeScript knows result is TryError here
  console.error(result.message);
  console.error(result.stack);
  console.error(result.source);
} else {
  // TypeScript knows result is the parsed value here
  console.log(result.someProperty);
}

isTrySuccess

isTrySuccess Signaturetypescript
function isTrySuccess<T>(value: TryResult<T, TryError>): value is T

Type guard function to check if a value is a successful result (not a TryError).

isTrySuccess Usagetypescript
const result = trySync(() => JSON.parse(jsonString));

if (isTrySuccess(result)) {
  // TypeScript knows result is the parsed value here
  console.log('Success:', result);
} else {
  // TypeScript knows result is TryError here
  console.error('Error:', result.message);
}

Common Patterns

Default Values

Default Value Patternstypescript
// Provide default value on error
function parseConfigWithDefault(jsonString: string) {
  const result = trySync(() => JSON.parse(jsonString));
  return isTryError(result) ? { defaultConfig: true } : result;
}

// Using ternary operator
const config = isTryError(parseResult) ? defaultConfig : parseResult;

Error Transformation

Error Transformationtypescript
function parseWithCustomError(jsonString: string) {
  const result = trySync(() => JSON.parse(jsonString));
  
  if (isTryError(result)) {
    return createTryError(
      'CONFIG_PARSE_ERROR',
      `Failed to parse configuration: ${result.message}`,
      { originalError: result, input: jsonString }
    );
  }
  
  return result;
}

Chaining Operations

Chaining Operationstypescript
function processData(input: string) {
  // Parse JSON
  const parseResult = trySync(() => JSON.parse(input));
  if (isTryError(parseResult)) return parseResult;
  
  // Validate structure
  const validateResult = trySync(() => validateSchema(parseResult));
  if (isTryError(validateResult)) return validateResult;
  
  // Transform data
  const transformResult = trySync(() => transformData(validateResult));
  return transformResult;
}

Multiple Operations

Processing Multiple Inputstypescript
function processMultipleInputs(inputs: string[]) {
  const results = [];
  const errors = [];
  
  for (const input of inputs) {
    const result = trySync(() => JSON.parse(input));
    if (isTryError(result)) {
      errors.push({ input, error: result });
    } else {
      results.push(result);
    }
  }
  
  return { results, errors };
}

Best Practices

✅ Do

  • • Always check for errors before using the result
  • • Use type guards for proper type narrowing
  • • Provide meaningful error messages
  • • Handle errors at the appropriate level
  • • Use early returns to avoid deep nesting

❌ Don't

  • • Access result properties without checking for errors first
  • • Ignore error cases in your code
  • • Use trySync for async operations (use tryAsync instead)
  • • Nest trySync calls unnecessarily
  • • Throw exceptions inside trySync callbacks

Performance

Zero Overhead: trySync has no performance impact for successful operations. Error cases have minimal overhead compared to traditional exception handling.

Performance Comparisontypescript
1// Performance comparison
2console.time('trySync');
3for (let i = 0; i < 1000000; i++) {
4  const result = trySync(() => JSON.parse('{"test": true}'));
5  if (!isTryError(result)) {
6    // Process result
7  }
8}
9console.timeEnd('trySync'); // ~50ms
10
11console.time('try/catch');
12for (let i = 0; i < 1000000; i++) {
13  try {
14    const result = JSON.parse('{"test": true}');
15    // Process result
16  } catch (error) {
17    // Handle error
18  }
19}
20console.timeEnd('try/catch'); // ~50ms (same for success cases)

Related APIs

tryAsync

For asynchronous operations that return promises

View tryAsync →

Error Creation

Creating custom errors and error factories

View Error API →