### Basic Setup and Error Definition Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Demonstrates the basic setup for conway-errors. It involves creating error contexts with predefined error types and then creating specific feature errors within an application context. ```typescript import { createError } from "conway-errors"; // Define your error types const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, ] as const); // Create your first error context const appErrors = createErrorContext("MyApp"); ``` -------------------------------- ### Simple Error Handling Example Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Illustrates a complete example of setting up error types, creating application and feature-specific errors, throwing them within a try-catch block, and logging their messages. This covers validation, network, and business logic errors. ```typescript import { createError } from "conway-errors"; // Configure error types for your application const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, { errorType: "BusinessLogicError" }, ] as const); // Create your application's root error context const appErrors = createErrorContext("ECommerceApp"); // Create specific errors const userRegistration = appErrors.feature("UserRegistration"); const paymentProcessing = appErrors.feature("PaymentProcessing"); // Throw contextual errors try { // Some validation logic throw userRegistration("ValidationError", "Email already exists"); } catch (error) { console.log(error.message); // Output: "ValidationError: ECommerceApp/UserRegistration: Email already exists" } // Log errors without throwing paymentProcessing("NetworkError", "Payment gateway timeout").emit(); ``` -------------------------------- ### PostHog Integration for Analytics and Error Tracking Source: https://context7.com/ivklgn/conway-errors/llms.txt Integrates Conway Errors with PostHog for product analytics and error tracking. This setup captures exceptions with user session context and also tracks them as custom events for detailed dashboard analysis. It requires 'posthog-js' and 'conway-errors' packages. ```typescript import { createError } from "conway-errors"; import posthog from "posthog-js"; const createErrorContext = createError( [ { errorType: "UserError" }, { errorType: "SystemError" }, { errorType: "NetworkError" } ] as const, { extendedParams: { appVersion: "3.0.0", platform: "web" }, handleEmit: (err, extendedParams) => { const { userId, sessionId, feature, severity = "error", ...additionalProps } = extendedParams || {}; // Capture exception event posthog.captureException(err, { $set: { error_count: "$increment" }, user_id: userId, session_id: sessionId, severity: severity, error_type: err.name, error_context: err.rootContext, error_feature: err.feature, error_path: err.contextsChunk, feature_area: feature, timestamp: Date.now(), ...additionalProps }); // Also track as custom event for dashboards posthog.capture("error_occurred", { error_name: err.name, error_message: err.message, error_path: err.contextsChunk, severity: severity, ...additionalProps }); } } ); const mobileApp = createErrorContext("MobileApp", { extendedParams: { platform: "mobile" } }); const userProfile = mobileApp.subcontext("UserProfile", { extendedParams: { feature: "profile_management" } }); const avatarUpload = userProfile.feature("AvatarUpload"); // Example: Error tracking with user session context async function uploadAvatar(file: File, user: User) { try { const uploaded = await uploadService.upload(file); // Track success event posthog.capture("avatar_uploaded", { user_id: user.id, file_size: file.size, file_type: file.type }); return uploaded; } catch (error) { avatarUpload("SystemError", "Failed to upload avatar", { originalError: error }).emit({ extendedParams: { userId: user.id, sessionId: user.sessionId, severity: "warning", fileSize: file.size, fileType: file.type, attemptCount: user.uploadAttempts + 1 } }); throw error; } } ``` -------------------------------- ### Custom Error Emission Handler with Sentry Integration Source: https://context7.com/ivklgn/conway-errors/llms.txt Illustrates how to customize the error emission behavior by providing a `handleEmit` function during the `createError` configuration. This example shows integration with Sentry for error monitoring, including setting user context, severity levels, and error details as tags, while also logging to the console in development. ```typescript import { createError } from "conway-errors"; import * as Sentry from "@sentry/nextjs"; const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" } ] as const, { handleEmit: (err, extendedParams) => { // Custom handling: send to Sentry with context Sentry.withScope(scope => { // Add custom tags from extended params if (extendedParams?.userId) { scope.setUser({ id: extendedParams.userId as string }); } if (extendedParams?.severity) { scope.setLevel(extendedParams.severity as Sentry.SeverityLevel); } // Add error context as tags scope.setTags({ errorContext: err.rootContext, errorFeature: err.feature, errorPath: err.contextsChunk }); Sentry.captureException(err); }); // Also log to console in development if (process.env.NODE_ENV === "development") { console.error(err); } } }); const appErrors = createErrorContext("MyApp"); const checkoutError = appErrors.feature("Checkout"); // Error automatically sent to Sentry when emitted checkoutError("BackendLogicError", "Payment processing failed").emit({ extendedParams: { userId: "user-456", severity: "error", transactionId: "txn-789" } }); ``` -------------------------------- ### Hierarchical Error Organization Example Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Demonstrates how to create nested error contexts using `subcontext` to build a hierarchical error structure. This allows for more granular organization of errors related to different parts of a project, like API errors and authentication errors. ```typescript import { createError } from "conway-errors"; // Setup error configuration const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" }, ] as const); // Create root context const errorContext = createErrorContext("MyProject"); // Create organized subcontexts const apiErrorContext = errorContext.subcontext("APIError"); const authErrorContext = errorContext.subcontext("AuthError"); // Create specific error functions const oauthError = authErrorContext.feature("OauthError"); const apiPaymentError = apiErrorContext.feature("APIPaymentError"); // Throw errors throw oauthError("FrontendLogicError", "User not found"); // Result: "FrontendLogicError: MyProject/AuthError/OauthError: User not found" throw apiPaymentError("BackendLogicError", "Payment already processed"); // Result: "BackendLogicError: MyProject/APIError/APIPaymentError: Payment already processed" ``` -------------------------------- ### Sentry Integration for Error Tracking with Conway Errors Source: https://context7.com/ivklgn/conway-errors/llms.txt Integrates Conway Errors with Sentry for robust error tracking. This setup preserves context, identifies users, and applies custom tags for effective filtering and analysis. It requires '@sentry/nextjs' and 'conway-errors' packages. ```typescript import { createError } from "conway-errors"; import * as Sentry from "@sentry/nextjs"; const createErrorContext = createError( [ { errorType: "ClientError" }, { errorType: "ServerError" }, { errorType: "ValidationError" } ] as const, { extendedParams: { environment: process.env.NODE_ENV, version: process.env.APP_VERSION }, handleEmit: (err, extendedParams) => { const { environment, version, severity = "error", userId, userEmail, action, component, ...customContext } = extendedParams || {}; Sentry.withScope(scope => { // Set user context if (userId || userEmail) { scope.setUser({ id: userId as string | undefined, email: userEmail as string | undefined }); } // Set severity level scope.setLevel(severity as Sentry.SeverityLevel); // Add tags for filtering scope.setTags({ environment: environment as string, version: version as string, errorType: err.name, errorContext: err.rootContext, errorFeature: err.feature, action: action as string | undefined, component: component as string | undefined }); // Add custom context scope.setContext("errorDetails", { fullPath: err.contextsChunk, originalError: err.originalError, ...customContext }); // Capture exception Sentry.captureException(err); }); } } ); const appErrors = createErrorContext("WebApp"); const checkoutFlow = appErrors.subcontext("Checkout"); const paymentStep = checkoutFlow.feature("Payment"); // Example usage with comprehensive context async function processPayment(paymentData: any) { try { const result = await stripeAPI.charge(paymentData); return result; } catch (error) { paymentStep("ServerError", "Payment processing failed", { originalError: error }).emit({ extendedParams: { userId: paymentData.userId, userEmail: paymentData.email, severity: "critical", action: "process_payment", component: "stripe_integration", amount: paymentData.amount, currency: paymentData.currency, paymentMethod: paymentData.method } }); throw error; } } ``` -------------------------------- ### Customize Error Message Formatting Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Allows for custom formatting of error messages by providing a `createMessagePostfix` function during error type definition. This example appends the original error's message to the formatted error string. ```typescript import { createError } from "conway-errors"; const createErrorContext = createError([ { errorType: "FrontendLogicError", createMessagePostfix: (originalError) => " >>> " + originalError?.message }, { errorType: "BackendLogicError" }, ] as const); const context = createErrorContext("FileUpload"); const uploadError = context.feature("AvatarUpload"); try { await uploadAvatar(); } catch (err) { throw uploadError("FrontendLogicError", "Failed to upload avatar", err); // Result: "FrontendLogicError: FileUpload/AvatarUpload: Failed to upload avatar >>> Network timeout" } ``` -------------------------------- ### Create Nested Error Contexts for Hierarchical Organization - TypeScript Source: https://context7.com/ivklgn/conway-errors/llms.txt This example shows how to create nested error contexts using the `subcontext` method provided by the error factory. This allows for deep hierarchical organization of errors, mirroring application structure. It demonstrates creating multiple levels of nesting and then defining feature-specific errors within these contexts. ```typescript import { createError } from "conway-errors"; const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" }, { errorType: "APIError" } ] as const); // Root context const projectErrors = createErrorContext("MyProject"); // Create subcontexts for logical grouping const apiErrors = projectErrors.subcontext("API"); const authErrors = projectErrors.subcontext("Auth"); // Further nesting const oauthErrors = authErrors.subcontext("OAuth"); const paymentAPIErrors = apiErrors.subcontext("Payment"); // Create feature errors const oauthLogin = oauthErrors.feature("LoginError"); const paymentCharge = paymentAPIErrors.feature("ChargeError"); // Hierarchical error paths throw oauthLogin("FrontendLogicError", "User not found"); // Result: "FrontendLogicError: MyProject/Auth/OAuth/LoginError: User not found" throw paymentCharge("BackendLogicError", "Payment already processed"); // Result: "BackendLogicError: MyProject/API/Payment/ChargeError: Payment already processed" ``` -------------------------------- ### Correct Usage of `as const` for Error Type Definitions (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README.md This example highlights the importance of using `as const` when defining error types with `conway-errors` to ensure proper type inference and prevent potential TypeScript errors. It shows the correct way to define an array of error types using a const assertion. ```typescript // ✅ Correct const createErrorContext = createError(["ValidationError"] as const); // ❌ Incorrect const createErrorContext = createError(["ValidationError"]); ``` -------------------------------- ### Create Error Context with Extended Parameters and Sentry Integration (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Demonstrates how to create a reusable error context with extended parameters and a custom handler for emitting errors. This example specifically shows integration with Sentry for error reporting, including setting tags, user information, and severity levels. Extended parameters are inherited and can be overridden by child contexts. ```typescript import { createError } from "conway-errors"; import * as Sentry from "@sentry/nextjs"; const createErrorContext = createError( ["FrontendLogicError", "BackendLogicError"], { extendedParams: { environment: process.env.NODE_ENV, version: "1.2.3" }, handleEmit: (err, extendedParams) => { const { environment, version, severity = "error", userId, action } = extendedParams; Sentry.withScope(scope => { scope.setTags({ environment, version, action }); scope.setUser({ id: userId }); scope.setLevel(severity); Sentry.captureException(err); }); }, } ); const paymentErrors = createErrorContext("Payment", { extendedParams: { service: "stripe" } }); const cardPayment = paymentErrors.feature("CardPayment", { extendedParams: { region: "us-east-1" } }); // Ошибка с контекстно-специфичными метаданными const error = cardPayment("BackendLogicError", "Сбой обработки платежа"); error.emit({ extendedParams: { userId: "user-123", action: "checkout", severity: "critical" } }); ``` -------------------------------- ### Hierarchical Extended Parameters for Metadata Propagation Source: https://context7.com/ivklgn/conway-errors/llms.txt Demonstrates how to use `extendedParams` to add custom metadata at different levels of the error hierarchy (global, service, subcontext, feature). It shows how these parameters are inherited and merged, with child contexts overriding parent values, and how they are included when emitting an error. This example includes integration with PostHog for capturing these enhanced error details. ```typescript import { createError } from "conway-errors"; import posthog from "posthog-js"; const createErrorContext = createError( [ { errorType: "ValidationError" }, { errorType: "NetworkError" }, { errorType: "ServerError" } ] as const, { // Global extended params for all errors extendedParams: { environment: process.env.NODE_ENV, appVersion: "2.1.0" }, handleEmit: (err, extendedParams) => { posthog.captureException(err, { ...extendedParams, errorPath: err.contextsChunk, timestamp: Date.now() }); } } ); // Root context with service identifier const paymentService = createErrorContext("PaymentService", { extendedParams: { service: "stripe", region: "us-east-1" } }); // Subcontext with team attribution const recurringBilling = paymentService.subcontext("RecurringBilling", { extendedParams: { team: "Billing Team", component: "Subscriptions" } }); // Feature with specific metadata const subscriptionCharge = recurringBilling.feature("SubscriptionCharge", { extendedParams: { retryable: true, maxRetries: 3 } }); // All parameters are merged: global + service + billing + feature + emit-time const error = subscriptionCharge("ServerError", "Stripe API unavailable"); error.emit({ extendedParams: { customerId: "cus_123", subscriptionId: "sub_456", attemptNumber: 2 } }); // PostHog receives all merged parameters: // { // environment: "production", // appVersion: "2.1.0", // service: "stripe", // region: "us-east-1", // team: "Billing Team", // component: "Subscriptions", // retryable: true, // maxRetries: 3, // customerId: "cus_123", // subscriptionId: "sub_456", // attemptNumber: 2, // errorPath: "PaymentService/RecurringBilling/SubscriptionCharge", // timestamp: 1234567890 // } ``` -------------------------------- ### Correctly Defining Error Types with `as const` Assertion (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Provides a code example demonstrating the correct way to define error types using `as const` with the `createError` function in TypeScript. This is crucial for ensuring that the string literals are preserved as distinct types, preventing potential TypeScript errors when dealing with custom error types and contexts. ```typescript // ✅ Правильно const createErrorContext = createError(["ValidationError"] as const); // ❌ Неправильно const createErrorContext = createError(["ValidationError"]); ``` -------------------------------- ### Установка conway-errors Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Команда для установки библиотеки conway-errors с использованием npm. Эта команда загружает пакет из реестра npm и добавляет его в зависимости вашего проекта. ```bash npm install conway-errors ``` -------------------------------- ### Create and Throw Errors Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Shows how to create a specific error (e.g., 'LoginError') within an application context and then throw it with a specific error type and message. The output demonstrates the structured format of the thrown error. ```typescript // Create an error const loginError = appErrors.feature("LoginError"); throw loginError("ValidationError", "Invalid email format"); // Result: ValidationError: MyApp/LoginError: Invalid email format ``` -------------------------------- ### Отдельные корневые контексты ошибок conway-errors Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Пример использования conway-errors с несколькими независимыми корневыми контекстами ошибок. Каждый контекст настраивается со своими типами ошибок и используется для конкретных API. ```typescript import { createError } from "conway-errors"; // Настройка типов ошибок, специфичных для API const createAPIErrorContext = createError([ { errorType: "MissingRequiredHeader" }, { errorType: "InvalidInput" }, { errorType: "InternalError" }, { errorType: "RateLimitExceeded" }, ] as const); // Создание контекстов ошибок для конкретных сервисов const authAPIErrors = createAPIErrorContext("AuthAPI"); const stockAPIErrors = createAPIErrorContext("StockAPI"); // Создание обработчиков ошибок для конкретных функций const loginError = authAPIErrors.feature("LoginError"); const registerError = authAPIErrors.feature("RegisterError"); const stockSearchError = stockAPIErrors.feature("StockSearchError"); // Обработка различных сценариев ошибок try { // Логика API вызова throw loginError("InvalidInput", "Неверный формат email"); } catch (error) { // Обработка ошибок валидации входа } // Логирование ошибок для мониторинга stockSearchError("RateLimitExceeded", "Превышена квота API").emit(); ``` -------------------------------- ### Organize Errors by Domain and Subcontext Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Demonstrates creating distinct error sets for different domains (e.g., Payment, Authentication) and further subdividing them into specific contexts and features. This promotes logical error grouping and isolation. ```typescript import { createError } from "conway-errors"; // Separate type sets for different contexts const createPaymentErrors = createError([ { errorType: "ValidationError" }, { errorType: "ProcessingError" }, { errorType: "GatewayError" }, ] as const); const createAuthErrors = createError([ { errorType: "AuthenticationError" }, { errorType: "AuthorizationError" }, { errorType: "TokenError" }, ] as const); // Payment domain errors const paymentErrors = createPaymentErrors("Payment"); const recurringPayments = paymentErrors.subcontext("Recurring"); const refunds = paymentErrors.subcontext("Refund"); const recurringError = recurringPayments.feature("RecurringPaymentError"); const refundError = refunds.feature("RefundError"); // Auth domain errors const authErrors = createAuthErrors("Authentication"); const oauthError = authErrors.feature("OAuthError"); // Usage examples throw recurringError("ProcessingError", "Card declined for recurring payment"); throw oauthError("TokenError", "OAuth token has expired"); ``` -------------------------------- ### Базовая настройка conway-errors Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Пример базовой настройки библиотеки conway-errors в TypeScript. Определяются типы ошибок, создается корневой контекст ошибок приложения и пример использования для выброса ошибки. ```typescript import { createError } from "conway-errors"; // Определите типы ошибок const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, ] as const); // Создайте ваш первый контекст ошибок const appErrors = createErrorContext("MyApp"); // Создайте ошибку const loginError = appErrors.feature("LoginError"); throw loginError("ValidationError", "Неверный формат email"); // Результат: ValidationError: MyApp/LoginError: Неверный формат email ``` -------------------------------- ### Organize Errors by Team and Component Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Shows how to associate errors with specific teams and components using `extendedParams` during subcontext creation or by creating team-specific root contexts. This enhances clarity for debugging and ownership. ```typescript import { createError } from "conway-errors"; const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" }, ] as const); const projectErrors = createErrorContext("MyProject"); // Method 1: Using extendedParams for team attribution (recommended) const authErrors = projectErrors.subcontext("Auth", { extendedParams: { team: "Platform Team", component: "Authentication" } }); const searchErrors = projectErrors.subcontext("Search", { extendedParams: { team: "User Experience Team", component: "Search" } }); // Method 2: Team-specific root contexts const platformErrors = createErrorContext("PlatformTeam"); const uxErrors = createErrorContext("UXTeam"); ``` -------------------------------- ### Separate Root Contexts for Different Services Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Illustrates how to create independent root error contexts for different services (e.g., Auth API, Stock API). This pattern is useful for managing errors in microservices or distinct modules within a larger application, ensuring clear separation. ```typescript import { createError } from "conway-errors"; // Configure API-specific error types const createAPIErrorContext = createError([ { errorType: "MissingRequiredHeader" }, { errorType: "InvalidInput" }, { errorType: "InternalError" }, { errorType: "RateLimitExceeded" }, ] as const); // Create service-specific error contexts const authAPIErrors = createAPIErrorContext("AuthAPI"); const stockAPIErrors = createAPIErrorContext("StockAPI"); // Create feature-specific error handlers const loginError = authAPIErrors.feature("LoginError"); const registerError = authAPIErrors.feature("RegisterError"); const stockSearchError = stockAPIErrors.feature("StockSearchError"); // Handle different error scenarios try { // API call logic throw loginError("InvalidInput", "Invalid email format"); } catch (error) { // Handle login validation errors } // Log errors for monitoring stockSearchError("RateLimitExceeded", "API quota exceeded").emit(); ``` -------------------------------- ### Integrate Error Tracking with PostHog Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Sets up `conway-errors` to send error events to PostHog, including user analytics data like `userId`, `sessionId`, and `feature`. The `handleEmit` function captures these details for detailed tracking. ```typescript import { createError } from "conway-errors"; import posthog from "posthog-js"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, { errorType: "BusinessLogicError" } ] as const, { extendedParams: { userId: null, sessionId: null, feature: null }, handleEmit: (err, extendedParams) => { const { userId, sessionId, feature, severity = "error" } = extendedParams; // Capture exception with PostHog posthog.captureException(err, { user_id: userId, session_id: sessionId, feature: feature, severity: severity, error_context: err.name, // Conway error context path timestamp: Date.now() }); }, }); const checkoutErrors = createErrorContext("Checkout", { extendedParams: { feature: "payment_flow" } }); const paymentError = checkoutErrors.feature("PaymentProcessing"); // Error with user context for PostHog analytics paymentError("NetworkError", "Payment gateway timeout").emit({ extendedParams: { userId: "user-123", sessionId: "session-456", severity: "critical" } }); ``` -------------------------------- ### Пример простой структуры ошибок conway-errors Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Демонстрирует создание и использование ошибок в conway-errors с простой структурой. Включает определение типов ошибок, создание контекстов и выброс/логирование ошибок. ```typescript import { createError } from "conway-errors"; // Настройте типы ошибок для вашего приложения const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, { errorType: "BusinessLogicError" }, ] as const); // Создайте корневой контекст ошибок приложения const appErrors = createErrorContext("ECommerceApp"); // Создайте конкретные ошибки const userRegistration = appErrors.feature("UserRegistration"); const paymentProcessing = appErrors.feature("PaymentProcessing"); // Выбрасывайте контекстуальные ошибки try { // Какая-то логика валидации throw userRegistration("ValidationError", "Email уже существует"); } catch (error) { console.log(error.message); // Вывод: "ValidationError: ECommerceApp/UserRegistration: Email уже существует" } // Логируйте ошибки без выброса paymentProcessing("NetworkError", "Таймаут платежного шлюза").emit(); ``` -------------------------------- ### Иерархическая организация ошибок conway-errors Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Показывает, как создавать иерархически организованные ошибки с помощью conway-errors. Демонстрируется создание подконтекстов и конкретных функций ошибок для более детальной структуры. ```typescript import { createError } from "conway-errors"; // Настройка конфигурации ошибок const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" }, ] as const); // Создание корневого контекста const errorContext = createErrorContext("MyProject"); // Создание организованных подконтекстов const apiErrorContext = errorContext.subcontext("APIError"); const authErrorContext = errorContext.subcontext("AuthError"); // Создание конкретных функций ошибок const oauthError = authErrorContext.feature("OauthError"); const apiPaymentError = apiErrorContext.feature("APIPaymentError"); // Выброс ошибок throw oauthError("FrontendLogicError", "Пользователь не найден"); // Результат: "FrontendLogicError: MyProject/AuthError/OauthError: Пользователь не найден" throw apiPaymentError("BackendLogicError", "Платеж уже обработан"); // Результат: "BackendLogicError: MyProject/APIError/APIPaymentError: Платеж уже обработан" ``` -------------------------------- ### Add Custom Metadata to Errors with Sentry Integration (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README.md This snippet demonstrates how to create error contexts with extended parameters and a custom handler to emit errors to Sentry. It shows how to define a base error context with global parameters and then create specific error types with their own metadata. The `handleEmit` function showcases integrating with Sentry for error reporting. ```typescript import { createError } from "conway-errors"; import * as Sentry from "@sentry/nextjs"; const createErrorContext = createError( ["FrontendLogicError", "BackendLogicError"], { extendedParams: { environment: process.env.NODE_ENV, version: "1.2.3" }, handleEmit: (err, extendedParams) => { const { environment, version, severity = "error", userId, action } = extendedParams; Sentry.withScope(scope => { scope.setTags({ environment, version, action }); scope.setUser({ id: userId }); scope.setLevel(severity); Sentry.captureException(err); }); }, } ); const paymentErrors = createErrorContext("Payment", { extendedParams: { service: "stripe" } }); const cardPayment = paymentErrors.feature("CardPayment", { extendedParams: { region: "us-east-1" } }); // Error with context-specific metadata const error = cardPayment("BackendLogicError", "Payment processing failed"); error.emit({ extendedParams: { userId: "user-123", action: "checkout", severity: "critical" } }); ``` -------------------------------- ### Integrate Error Monitoring with Sentry Source: https://github.com/ivklgn/conway-errors/blob/main/README.md Configures `conway-errors` to automatically report errors to Sentry by overriding the `.emit()` method with a custom `handleEmit` function. This ensures all emitted errors are captured by Sentry. ```typescript import { createError } from "conway-errors"; import * as Sentry from "@sentry/nextjs"; const createErrorContext = createError([ { errorType: "FrontendLogicError" }, { errorType: "BackendLogicError" } ] as const, { // Custom error handling for monitoring handleEmit: (err) => { Sentry.captureException(err); }, }); const appErrors = createErrorContext("MyApp"); const userError = appErrors.feature("UserAction"); // Automatically logs to Sentry when using emit() userError("FrontendLogicError", "Form validation failed").emit(); ``` -------------------------------- ### Custom Error Message Formatting with createMessagePostfix - TypeScript Source: https://context7.com/ivklgn/conway-errors/llms.txt Demonstrates how to customize error message postfixes for different error types using `createMessagePostfix`. This is useful for adding contextual information or chaining original errors. It requires the `conway-errors` library. The function takes an `originalError` as input and returns a string to be appended to the error message. ```typescript import { createError } from "conway-errors"; const createErrorContext = createError([ { errorType: "NetworkError", createMessagePostfix: (originalError) => { if (originalError instanceof Error) { return ` | Caused by: ${originalError.message}`; } return ""; } }, { errorType: "ValidationError", createMessagePostfix: (originalError) => { if (originalError && typeof originalError === "object" && "details" in originalError) { const details = originalError.details as Record; return ` | Details: ${JSON.stringify(details)}`; } return ""; } }, { errorType: "ServerError" } ] as const); const apiService = createErrorContext("APIService"); const dataFetch = apiService.feature("DataFetch"); // Example 1: Network error with original error try { await fetch("https://api.example.com/data"); } catch (networkError) { throw dataFetch("NetworkError", "Failed to fetch user data", { originalError: networkError }); // Message: "NetworkError: APIService/DataFetch: Failed to fetch user data | Caused by: fetch failed" } // Example 2: Validation error with custom details try { validateUserInput(data); } catch (validationError) { throw dataFetch("ValidationError", "Invalid user input", { originalError: { details: { field: "email", constraint: "format", value: "invalid-email" } } }); // Message: "ValidationError: APIService/DataFetch: Invalid user input | Details: {\"field\":\"email\",\"constraint\":\"format\",\"value\":\"invalid-email\"}" } // Example 3: Server error without postfix throw dataFetch("ServerError", "Internal server error"); // Message: "ServerError: APIService/DataFetch: Internal server error" ``` -------------------------------- ### Type-Safe Error Handling with Subcontext Constraints (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README.md This code illustrates how to leverage TypeScript's `AnyFeatureOfSubcontext` utility to ensure type safety when handling errors within specific subcontexts. It demonstrates creating nested error contexts and defining functions that only accept errors originating from a particular subcontext, preventing accidental misuse of error types. ```typescript import { createError, AnyFeatureOfSubcontext } from "conway-errors"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "ProcessingError" }, ] as const); const appErrors = createErrorContext("App"); const authErrors = appErrors.subcontext("Auth"); const loginError = authErrors.feature("LoginError"); const generalError = appErrors.feature("GeneralError"); // Type-safe error handler for auth-specific features function handleAuthError(errorFeature: AnyFeatureOfSubcontext) { // Only accepts features from authErrors subcontext } handleAuthError(loginError); // ✅ Valid handleAuthError(generalError); // ❌ TypeScript error ``` -------------------------------- ### Create Error Context Factory with Error Types - TypeScript Source: https://context7.com/ivklgn/conway-errors/llms.txt This snippet demonstrates how to create a factory function for generating error contexts with predefined error types. It utilizes the `createError` function from the 'conway-errors' library. The factory can then be used to create root contexts, feature-specific contexts, and throw structured errors with hierarchical paths. ```typescript import { createError } from "conway-errors"; // Define error types for your application const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" }, { errorType: "BusinessLogicError" } ] as const); // Create root context const appErrors = createErrorContext("ECommerceApp"); // Create feature-specific errors const userRegistration = appErrors.feature("UserRegistration"); const paymentProcessing = appErrors.feature("PaymentProcessing"); // Throw structured errors try { throw userRegistration("ValidationError", "Email already exists"); } catch (error) { console.log(error.message); // Output: "ValidationError: ECommerceApp/UserRegistration: Email already exists" console.log(error.name); // "ValidationError" } // Log without throwing paymentProcessing("NetworkError", "Payment gateway timeout").emit(); ``` -------------------------------- ### Type-Safe Error Handling with Subcontexts and TypeScript Utility Types (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Illustrates how to leverage `conway-errors` with TypeScript for type-safe error handling. It shows the creation of error contexts and subcontexts, demonstrating the use of `AnyFeatureOfSubcontext` to ensure that error handlers only accept errors belonging to a specific subcontext. This enhances code maintainability and prevents runtime errors. ```typescript import { createError, AnyFeatureOfSubcontext } from "conway-errors"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "ProcessingError" }, ] as const); const appErrors = createErrorContext("App"); const authErrors = appErrors.subcontext("Auth"); const loginError = authErrors.feature("LoginError"); const generalError = appErrors.feature("GeneralError"); // Типобезопасный обработчик ошибок для функций, специфичных для аутентификации function handleAuthError(errorFeature: AnyFeatureOfSubcontext) { // Принимает только функции из подконтекста authErrors } handleAuthError(loginError); // ✅ Валидно handleAuthError(generalError); // ❌ Ошибка TypeScript ``` -------------------------------- ### Create Feature-Specific Error Functions and Chain Errors - TypeScript Source: https://context7.com/ivklgn/conway-errors/llms.txt This snippet illustrates creating feature-specific error functions using the `feature` method. It demonstrates how to use these functions with different error types, including handling original errors through the `originalError` option for chaining. Extended parameters can also be attached for enhanced monitoring. ```typescript import { createError } from "conway-errors"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "DatabaseError" }, { errorType: "AuthenticationError" } ] as const); const userService = createErrorContext("UserService"); const authContext = userService.subcontext("Authentication"); // Create feature-specific error functions const loginError = authContext.feature("Login"); const registerError = authContext.feature("Register"); // Use with different error types try { const email = "invalid-email"; if (!email.includes("@")) { throw loginError("ValidationError", "Invalid email format"); } } catch (error) { console.error(error.message); // "ValidationError: UserService/Authentication/Login: Invalid email format" } // With original error chaining try { await database.findUser(userId); } catch (dbError) { throw loginError("DatabaseError", "Failed to fetch user", { originalError: dbError }); } // With extended parameters for monitoring const error = registerError("AuthenticationError", "Email already registered"); error.emit({ extendedParams: { userId: "user-123", severity: "warning", attemptCount: 3 } }); ``` -------------------------------- ### Type-Safe Error Handling with AnyFeatureOfSubcontext - TypeScript Source: https://context7.com/ivklgn/conway-errors/llms.txt Introduces `AnyFeatureOfSubcontext`, a TypeScript utility for creating functions that are type-safe with respect to error features from specific subcontexts. This prevents errors from being handled by the wrong error types. It requires the `conway-errors` library. ```typescript import { createError, AnyFeatureOfSubcontext } from "conway-errors"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "ProcessingError" }, { errorType: "AuthError" } ] as const); const appErrors = createErrorContext("App"); const authErrors = appErrors.subcontext("Authentication"); const paymentErrors = appErrors.subcontext("Payment"); // Create features const loginError = authErrors.feature("Login"); const registerError = authErrors.feature("Register"); const chargeError = paymentErrors.feature("Charge"); const refundError = paymentErrors.feature("Refund"); // Type-safe handler that only accepts auth errors function handleAuthError( errorFeature: AnyFeatureOfSubcontext, context: { userId?: string } ) { const error = errorFeature("AuthError", "Authentication failed"); error.emit({ extendedParams: context }); } // Type-safe handler for payment errors only function handlePaymentError( errorFeature: AnyFeatureOfSubcontext, amount: number ) { const error = errorFeature("ProcessingError", `Failed to process $${amount}`); error.emit(); } // Valid: loginError is from authErrors subcontext handleAuthError(loginError, { userId: "123" }); // Valid: registerError is from authErrors subcontext handleAuthError(registerError, { userId: "456" }); // Valid: chargeError is from paymentErrors subcontext handlePaymentError(chargeError, 99.99); // TypeScript Error: chargeError is not from authErrors subcontext // handleAuthError(chargeError, { userId: "789" }); // TypeScript Error: loginError is not from paymentErrors subcontext // handlePaymentError(loginError, 49.99); // Example: Error routing system type ErrorRouter = { auth: AnyFeatureOfSubcontext; payment: AnyFeatureOfSubcontext; }; function routeError(router: ErrorRouter, domain: keyof ErrorRouter, message: string) { if (domain === "auth") { const error = router.auth("AuthError", message); error.emit({ extendedParams: { domain: "authentication" } }); } else if (domain === "payment") { const error = router.payment("ProcessingError", message); error.emit({ extendedParams: { domain: "payment" } }); } } routeError( { auth: loginError, payment: chargeError }, "auth", "Invalid credentials" ); ``` -------------------------------- ### TypeScript Type Guard for Conway Errors Source: https://context7.com/ivklgn/conway-errors/llms.txt Demonstrates how to use the `isConwayError` type guard to differentiate Conway errors from standard JavaScript errors within an application's error handling logic. It shows how to access specific properties of a Conway error, such as its name, context, feature, and extended parameters. ```typescript import { createError, isConwayError } from "conway-errors"; const createErrorContext = createError([ { errorType: "ValidationError" }, { errorType: "NetworkError" } ] as const); const appErrors = createErrorContext("App"); const apiError = appErrors.feature("API"); function handleError(error: unknown) { if (isConwayError(error)) { // TypeScript knows this is IConwayError console.log("Conway Error:", error.name); console.log("Context:", error.rootContext); console.log("Feature:", error.feature); console.log("Full path:", error.contextsChunk); // Access extended parameters if (error.extendedParams) { console.log("Metadata:", error.extendedParams); } // Emit to monitoring error.emit(); } else if (error instanceof Error) { console.log("Standard Error:", error.message); } else { console.log("Unknown error type"); } } try { throw apiError("NetworkError", "Connection timeout"); } catch (error) { handleError(error); // Outputs Conway Error details } try { throw new Error("Generic error"); } catch (error) { handleError(error); // Outputs Standard Error } ``` -------------------------------- ### Defining Custom Error Types with Objects and `as const` (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README.md This snippet demonstrates the correct method for defining custom error types when using object literals with `conway-errors`. It emphasizes the use of `as const` to ensure that the error types are precisely inferred by TypeScript, avoiding potential type mismatches. ```typescript // ✅ Correct const createErrorContext = createError([ { errorType: "CustomError" }, { errorType: "AnotherError" } ] as const); ``` -------------------------------- ### Defining Custom Error Types with Object Literals and `as const` (TypeScript) Source: https://github.com/ivklgn/conway-errors/blob/main/README_RU.md Shows the correct method for defining custom error types using object literals within an array, combined with the `as const` assertion. This approach ensures proper type inference and compatibility when creating complex error structures with `conway-errors`. ```typescript // ✅ Правильно const createErrorContext = createError([ { errorType: "CustomError" }, { errorType: "AnotherError" } ] as const); ```