try-error Documentation

Error Codes Reference

Complete reference of standard error types and codes used in try-error

Standard Error Types

try-error provides a set of standard error types that cover common error scenarios. These types help categorize errors for better handling and debugging.

ValidationError

Used when input validation fails or data doesn't meet required criteria.

// Example usage
const result = trySync(() => {
  if (!email.includes('@')) {
    throw createTryError('ValidationError', 'Invalid email format', {
      field: 'email',
      value: email,
      rule: 'must_contain_at_symbol'
    });
  }
  return email;
});

Common Context Fields

  • field - The field that failed validation
  • value - The invalid value
  • rule - The validation rule that was violated
  • expected - What was expected

NetworkError

Used for network-related failures like HTTP requests, timeouts, or connectivity issues.

// Example usage
const result = await tryAsync(async () => {
  const response = await fetch('/api/users');
  if (!response.ok) {
    throw createTryError('NetworkError', 'Failed to fetch users', {
      url: '/api/users',
      status: response.status,
      statusText: response.statusText,
      method: 'GET'
    });
  }
  return response.json();
});

Common Context Fields

  • url - The URL that was requested
  • status - HTTP status code
  • statusText - HTTP status text
  • method - HTTP method used
  • timeout - Whether the request timed out

AuthenticationError

Used when authentication fails or credentials are invalid.

// Example usage
const result = await tryAsync(async () => {
  const token = getAuthToken();
  if (!token || isTokenExpired(token)) {
    throw createTryError('AuthenticationError', 'Authentication required', {
      reason: token ? 'token_expired' : 'no_token',
      userId: getCurrentUserId()
    });
  }
  return validateToken(token);
});

Common Context Fields

  • reason - Why authentication failed
  • userId - User ID if available
  • tokenExpired - Whether token is expired
  • provider - Authentication provider

AuthorizationError

Used when a user is authenticated but lacks permission for a specific action.

// Example usage
const result = trySync(() => {
  if (!user.hasPermission('admin')) {
    throw createTryError('AuthorizationError', 'Insufficient permissions', {
      userId: user.id,
      requiredPermission: 'admin',
      userPermissions: user.permissions,
      resource: 'admin_panel'
    });
  }
  return accessAdminPanel();
});

Common Context Fields

  • userId - ID of the user attempting access
  • requiredPermission - Permission needed
  • userPermissions - User's current permissions
  • resource - Resource being accessed
  • action - Action being attempted

NotFoundError

Used when a requested resource cannot be found.

// Example usage
const result = await tryAsync(async () => {
  const user = await database.findUser(userId);
  if (!user) {
    throw createTryError('NotFoundError', 'User not found', {
      resourceType: 'user',
      resourceId: userId,
      searchCriteria: { id: userId }
    });
  }
  return user;
});

Common Context Fields

  • resourceType - Type of resource (user, post, etc.)
  • resourceId - ID of the missing resource
  • searchCriteria - Criteria used to search
  • suggestions - Alternative resources

ConflictError

Used when an operation conflicts with the current state of the resource.

// Example usage
const result = await tryAsync(async () => {
  const existingUser = await database.findUserByEmail(email);
  if (existingUser) {
    throw createTryError('ConflictError', 'Email already in use', {
      field: 'email',
      value: email,
      conflictingResourceId: existingUser.id,
      conflictType: 'unique_constraint'
    });
  }
  return database.createUser({ email, name });
});

Common Context Fields

  • field - Field causing the conflict
  • value - Conflicting value
  • conflictingResourceId - ID of conflicting resource
  • conflictType - Type of conflict

RateLimitError

Used when rate limiting is triggered due to too many requests.

// Example usage
const result = await tryAsync(async () => {
  if (requestCount > rateLimit) {
    throw createTryError('RateLimitError', 'Rate limit exceeded', {
      limit: rateLimit,
      window: '1 hour',
      requestCount,
      resetTime: Date.now() + 3600000,
      clientId: getClientId()
    });
  }
  return processRequest();
});

Common Context Fields

  • limit - Maximum allowed requests
  • window - Time window for the limit
  • requestCount - Current request count
  • resetTime - When the limit resets
  • clientId - Identifier for the client

HTTP Status Code Mapping

Recommended HTTP status codes for each error type when building APIs.

Error TypeHTTP StatusDescription
ValidationError400 Bad RequestClient sent invalid data
AuthenticationError401 UnauthorizedAuthentication required
AuthorizationError403 ForbiddenInsufficient permissions
NotFoundError404 Not FoundResource doesn't exist
ConflictError409 ConflictResource state conflict
RateLimitError429 Too Many RequestsRate limit exceeded
NetworkError502/503/504External service issues
Error (generic)500 Internal Server ErrorUnexpected server error

Creating Custom Error Types

You can create custom error types for domain-specific errors in your application.

// Define custom error types
export const CustomErrorTypes = {
  PAYMENT_FAILED: 'PaymentError',
  INVENTORY_INSUFFICIENT: 'InventoryError',
  SUBSCRIPTION_EXPIRED: 'SubscriptionError',
  FEATURE_DISABLED: 'FeatureError',
  MAINTENANCE_MODE: 'MaintenanceError'
} as const;

// Usage examples
const paymentResult = await tryAsync(async () => {
  const payment = await processPayment(amount, cardToken);
  if (!payment.success) {
    throw createTryError(CustomErrorTypes.PAYMENT_FAILED, 'Payment processing failed', {
      amount,
      cardLast4: payment.cardLast4,
      declineReason: payment.declineReason,
      transactionId: payment.transactionId
    });
  }
  return payment;
});

const inventoryResult = trySync(() => {
  if (product.stock < quantity) {
    throw createTryError(CustomErrorTypes.INVENTORY_INSUFFICIENT, 'Not enough stock', {
      productId: product.id,
      requested: quantity,
      available: product.stock,
      restockDate: product.restockDate
    });
  }
  return reserveInventory(product, quantity);
});

Best Practices for Custom Error Types

  • • Use descriptive, domain-specific names
  • • Follow a consistent naming convention (e.g., PascalCase + "Error")
  • • Include relevant context data for debugging
  • • Document the error type and when it's used
  • • Consider the HTTP status code mapping for API errors

Error Code Utilities

Utility functions for working with error codes and types.

// Check if error is of specific type
function isErrorType(error: TryError, type: string): boolean {
  return error.type === type;
}

// Get HTTP status code from error type
function getHttpStatusFromError(error: TryError): number {
  const statusMap: Record<string, number> = {
    ValidationError: 400,
    AuthenticationError: 401,
    AuthorizationError: 403,
    NotFoundError: 404,
    ConflictError: 409,
    RateLimitError: 429,
    NetworkError: 502,
  };
  
  return statusMap[error.type] || 500;
}

// Create error response for APIs
function createErrorResponse(error: TryError) {
  return {
    error: {
      type: error.type,
      message: error.message,
      timestamp: error.timestamp,
      ...(process.env.NODE_ENV === 'development' && {
        stack: error.stack,
        context: error.context
      })
    }
  };
}

// Usage
if (isTryError(result)) {
  const status = getHttpStatusFromError(result);
  const response = createErrorResponse(result);
  res.status(status).json(response);
}

Related Pages

Custom Error Types

Learn how to create and use custom error types

View Custom Errors →

Error Creation

API reference for creating errors

View Error API →

Integration Guides

How to integrate error codes with frameworks

View Integration →