@umituz/react-native-exception 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ümit UZ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @umituz/react-native-exception
2
+
3
+ Exception handling and error tracking for React Native apps.
4
+
5
+ ## Features
6
+
7
+ - Centralized exception handling
8
+ - Error boundary component
9
+ - Exception store with Zustand
10
+ - Error categorization and severity levels
11
+ - Exception reporting utilities
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @umituz/react-native-exception
17
+ ```
18
+
19
+ ## Peer Dependencies
20
+
21
+ - `react` >= 18.2.0
22
+ - `react-native` >= 0.74.0
23
+ - `zustand` >= 5.0.2
24
+
25
+ ## Usage
26
+
27
+ ### Error Boundary
28
+
29
+ ```typescript
30
+ import { ErrorBoundary } from '@umituz/react-native-exception';
31
+
32
+ <ErrorBoundary>
33
+ <YourApp />
34
+ </ErrorBoundary>
35
+ ```
36
+
37
+ ### Exception Service
38
+
39
+ ```typescript
40
+ import { exceptionService } from '@umituz/react-native-exception';
41
+
42
+ try {
43
+ // Your code
44
+ } catch (error) {
45
+ exceptionService.handleException(
46
+ error,
47
+ 'error',
48
+ 'business-logic',
49
+ { userId: '123' }
50
+ );
51
+ }
52
+ ```
53
+
54
+ ### Exception Store
55
+
56
+ ```typescript
57
+ import { useExceptionStore } from '@umituz/react-native-exception';
58
+
59
+ const { exceptions, lastError } = useExceptionStore();
60
+ ```
61
+
62
+ ## License
63
+
64
+ MIT
65
+
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Exception Entity - Domain Layer
3
+ * Pure business logic representation of errors and exceptions
4
+ */
5
+ export type ExceptionSeverity = 'fatal' | 'error' | 'warning' | 'info';
6
+ export type ExceptionCategory = 'network' | 'validation' | 'authentication' | 'authorization' | 'business-logic' | 'system' | 'storage' | 'unknown';
7
+ export interface ExceptionContext {
8
+ userId?: string;
9
+ screen?: string;
10
+ action?: string;
11
+ componentStack?: string;
12
+ metadata?: Record<string, any>;
13
+ }
14
+ export interface ExceptionEntity {
15
+ id: string;
16
+ message: string;
17
+ stack?: string;
18
+ severity: ExceptionSeverity;
19
+ category: ExceptionCategory;
20
+ context: ExceptionContext;
21
+ timestamp: Date;
22
+ handled: boolean;
23
+ reported: boolean;
24
+ }
25
+ export interface ErrorLog {
26
+ id: string;
27
+ exceptionId: string;
28
+ userId?: string;
29
+ message: string;
30
+ stack?: string;
31
+ severity: ExceptionSeverity;
32
+ category: ExceptionCategory;
33
+ context: ExceptionContext;
34
+ createdAt: Date;
35
+ }
36
+ /**
37
+ * Factory function to create an exception entity
38
+ */
39
+ export declare function createException(error: Error, severity?: ExceptionSeverity, category?: ExceptionCategory, context?: ExceptionContext): ExceptionEntity;
40
+ /**
41
+ * Factory function to create an error log
42
+ */
43
+ export declare function createErrorLog(exception: ExceptionEntity): ErrorLog;
44
+ /**
45
+ * Determine if exception should be reported
46
+ */
47
+ export declare function shouldReportException(exception: ExceptionEntity): boolean;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ /**
3
+ * Exception Entity - Domain Layer
4
+ * Pure business logic representation of errors and exceptions
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.createException = createException;
8
+ exports.createErrorLog = createErrorLog;
9
+ exports.shouldReportException = shouldReportException;
10
+ /**
11
+ * Factory function to create an exception entity
12
+ */
13
+ function createException(error, severity = 'error', category = 'unknown', context = {}) {
14
+ return {
15
+ id: crypto.randomUUID(),
16
+ message: error.message,
17
+ stack: error.stack,
18
+ severity,
19
+ category,
20
+ context,
21
+ timestamp: new Date(),
22
+ handled: false,
23
+ reported: false,
24
+ };
25
+ }
26
+ /**
27
+ * Factory function to create an error log
28
+ */
29
+ function createErrorLog(exception) {
30
+ return {
31
+ id: crypto.randomUUID(),
32
+ exceptionId: exception.id,
33
+ userId: exception.context.userId,
34
+ message: exception.message,
35
+ stack: exception.stack,
36
+ severity: exception.severity,
37
+ category: exception.category,
38
+ context: exception.context,
39
+ createdAt: new Date(),
40
+ };
41
+ }
42
+ /**
43
+ * Determine if exception should be reported
44
+ */
45
+ function shouldReportException(exception) {
46
+ // Don't report warnings or info
47
+ if (exception.severity === 'warning' || exception.severity === 'info') {
48
+ return false;
49
+ }
50
+ // Don't report validation errors (user errors)
51
+ if (exception.category === 'validation') {
52
+ return false;
53
+ }
54
+ // Report everything else
55
+ return true;
56
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Exception Repository Interface
3
+ * Defines contracts for error logging and reporting
4
+ */
5
+ import type { ExceptionEntity, ErrorLog } from '../entities/ExceptionEntity';
6
+ export interface ExceptionRepositoryError extends Error {
7
+ code: 'LOG_FAILED' | 'REPORT_FAILED' | 'FETCH_FAILED';
8
+ }
9
+ export type ExceptionResult<T> = {
10
+ success: true;
11
+ data: T;
12
+ } | {
13
+ success: false;
14
+ error: ExceptionRepositoryError;
15
+ };
16
+ export interface IExceptionRepository {
17
+ /**
18
+ * Log an exception
19
+ */
20
+ logException(exception: ExceptionEntity): Promise<ExceptionResult<ErrorLog>>;
21
+ /**
22
+ * Report exception to external service (e.g., Sentry)
23
+ */
24
+ reportException(exception: ExceptionEntity): Promise<ExceptionResult<boolean>>;
25
+ /**
26
+ * Get error logs for a user
27
+ */
28
+ getErrorLogs(userId: string, limit?: number): Promise<ExceptionResult<ErrorLog[]>>;
29
+ /**
30
+ * Get recent exceptions
31
+ */
32
+ getRecentExceptions(limit?: number): Promise<ExceptionResult<ExceptionEntity[]>>;
33
+ /**
34
+ * Clear error logs
35
+ */
36
+ clearErrorLogs(userId: string): Promise<ExceptionResult<boolean>>;
37
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * Exception Repository Interface
4
+ * Defines contracts for error logging and reporting
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @umituz/react-native-exception - Public API
3
+ *
4
+ * Exception handling and error tracking for React Native apps
5
+ *
6
+ * Usage:
7
+ * import { ErrorBoundary, exceptionService, useExceptionStore } from '@umituz/react-native-exception';
8
+ */
9
+ export type { ExceptionEntity, ErrorLog, ExceptionContext, ExceptionSeverity, ExceptionCategory, } from './domain/entities/ExceptionEntity';
10
+ export { createException, createErrorLog, shouldReportException, } from './domain/entities/ExceptionEntity';
11
+ export type { IExceptionRepository, ExceptionRepositoryError, ExceptionResult, } from './domain/repositories/IExceptionRepository';
12
+ export { useExceptionStore, useExceptions } from './infrastructure/storage/ExceptionStore';
13
+ export { ExceptionService, exceptionService } from './infrastructure/services/ExceptionService';
14
+ export { ErrorBoundary } from './presentation/components/ErrorBoundary';
package/lib/index.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ /**
3
+ * @umituz/react-native-exception - Public API
4
+ *
5
+ * Exception handling and error tracking for React Native apps
6
+ *
7
+ * Usage:
8
+ * import { ErrorBoundary, exceptionService, useExceptionStore } from '@umituz/react-native-exception';
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.ErrorBoundary = exports.exceptionService = exports.ExceptionService = exports.useExceptions = exports.useExceptionStore = exports.shouldReportException = exports.createErrorLog = exports.createException = void 0;
12
+ var ExceptionEntity_1 = require("./domain/entities/ExceptionEntity");
13
+ Object.defineProperty(exports, "createException", { enumerable: true, get: function () { return ExceptionEntity_1.createException; } });
14
+ Object.defineProperty(exports, "createErrorLog", { enumerable: true, get: function () { return ExceptionEntity_1.createErrorLog; } });
15
+ Object.defineProperty(exports, "shouldReportException", { enumerable: true, get: function () { return ExceptionEntity_1.shouldReportException; } });
16
+ // =============================================================================
17
+ // INFRASTRUCTURE LAYER EXPORTS
18
+ // =============================================================================
19
+ // State Store (Zustand)
20
+ var ExceptionStore_1 = require("./infrastructure/storage/ExceptionStore");
21
+ Object.defineProperty(exports, "useExceptionStore", { enumerable: true, get: function () { return ExceptionStore_1.useExceptionStore; } });
22
+ Object.defineProperty(exports, "useExceptions", { enumerable: true, get: function () { return ExceptionStore_1.useExceptions; } });
23
+ // Services
24
+ var ExceptionService_1 = require("./infrastructure/services/ExceptionService");
25
+ Object.defineProperty(exports, "ExceptionService", { enumerable: true, get: function () { return ExceptionService_1.ExceptionService; } });
26
+ Object.defineProperty(exports, "exceptionService", { enumerable: true, get: function () { return ExceptionService_1.exceptionService; } });
27
+ // =============================================================================
28
+ // PRESENTATION LAYER EXPORTS
29
+ // =============================================================================
30
+ // Components
31
+ var ErrorBoundary_1 = require("./presentation/components/ErrorBoundary");
32
+ Object.defineProperty(exports, "ErrorBoundary", { enumerable: true, get: function () { return ErrorBoundary_1.ErrorBoundary; } });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Exception Service - Infrastructure Layer
3
+ * Centralized exception handling and reporting
4
+ */
5
+ import type { ExceptionContext, ExceptionSeverity, ExceptionCategory } from '../../domain/entities/ExceptionEntity';
6
+ export declare class ExceptionService {
7
+ private static instance;
8
+ private constructor();
9
+ static getInstance(): ExceptionService;
10
+ /**
11
+ * Handle an exception
12
+ */
13
+ handleException(error: Error, severity?: ExceptionSeverity, category?: ExceptionCategory, context?: ExceptionContext): void;
14
+ /**
15
+ * Report exception to external service (e.g., Sentry)
16
+ */
17
+ private reportException;
18
+ /**
19
+ * Handle network errors
20
+ */
21
+ handleNetworkError(error: Error, context?: ExceptionContext): void;
22
+ /**
23
+ * Handle validation errors
24
+ */
25
+ handleValidationError(error: Error, context?: ExceptionContext): void;
26
+ /**
27
+ * Handle storage/permission errors
28
+ */
29
+ handleStorageError(error: Error, context?: ExceptionContext): void;
30
+ /**
31
+ * Handle fatal errors
32
+ */
33
+ handleFatalError(error: Error, context?: ExceptionContext): void;
34
+ /**
35
+ * Clear all exceptions
36
+ */
37
+ clearExceptions(): void;
38
+ }
39
+ export declare const exceptionService: ExceptionService;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Exception Service - Infrastructure Layer
4
+ * Centralized exception handling and reporting
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.exceptionService = exports.ExceptionService = void 0;
8
+ const ExceptionEntity_1 = require("../../domain/entities/ExceptionEntity");
9
+ const ExceptionStore_1 = require("../storage/ExceptionStore");
10
+ class ExceptionService {
11
+ constructor() { }
12
+ static getInstance() {
13
+ if (!ExceptionService.instance) {
14
+ ExceptionService.instance = new ExceptionService();
15
+ }
16
+ return ExceptionService.instance;
17
+ }
18
+ /**
19
+ * Handle an exception
20
+ */
21
+ handleException(error, severity = 'error', category = 'unknown', context = {}) {
22
+ const exception = (0, ExceptionEntity_1.createException)(error, severity, category, context);
23
+ // Add to store
24
+ ExceptionStore_1.useExceptionStore.getState().addException(exception);
25
+ // Report to external service if needed
26
+ if ((0, ExceptionEntity_1.shouldReportException)(exception)) {
27
+ this.reportException(exception);
28
+ }
29
+ // Mark as handled
30
+ ExceptionStore_1.useExceptionStore.getState().markAsHandled(exception.id);
31
+ }
32
+ /**
33
+ * Report exception to external service (e.g., Sentry)
34
+ */
35
+ async reportException(exception) {
36
+ try {
37
+ // Mark as reported
38
+ ExceptionStore_1.useExceptionStore.getState().markAsReported(exception.id);
39
+ }
40
+ catch (error) {
41
+ // Silent failure
42
+ }
43
+ }
44
+ /**
45
+ * Handle network errors
46
+ */
47
+ handleNetworkError(error, context = {}) {
48
+ this.handleException(error, 'error', 'network', context);
49
+ }
50
+ /**
51
+ * Handle validation errors
52
+ */
53
+ handleValidationError(error, context = {}) {
54
+ this.handleException(error, 'warning', 'validation', context);
55
+ }
56
+ /**
57
+ * Handle storage/permission errors
58
+ */
59
+ handleStorageError(error, context = {}) {
60
+ this.handleException(error, 'error', 'storage', context);
61
+ }
62
+ /**
63
+ * Handle fatal errors
64
+ */
65
+ handleFatalError(error, context = {}) {
66
+ this.handleException(error, 'fatal', 'system', context);
67
+ }
68
+ /**
69
+ * Clear all exceptions
70
+ */
71
+ clearExceptions() {
72
+ ExceptionStore_1.useExceptionStore.getState().clearExceptions();
73
+ }
74
+ }
75
+ exports.ExceptionService = ExceptionService;
76
+ exports.exceptionService = ExceptionService.getInstance();
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Exception Store - Zustand State Management
3
+ * Global exception tracking and error state
4
+ */
5
+ import type { ExceptionEntity } from '../../domain/entities/ExceptionEntity';
6
+ interface ExceptionStore {
7
+ exceptions: ExceptionEntity[];
8
+ lastError: ExceptionEntity | null;
9
+ errorCount: number;
10
+ addException: (exception: ExceptionEntity) => void;
11
+ markAsHandled: (exceptionId: string) => void;
12
+ markAsReported: (exceptionId: string) => void;
13
+ clearExceptions: () => void;
14
+ getExceptionsByCategory: (category: string) => ExceptionEntity[];
15
+ getUnhandledExceptions: () => ExceptionEntity[];
16
+ }
17
+ export declare const useExceptionStore: import("zustand").UseBoundStore<import("zustand").StoreApi<ExceptionStore>>;
18
+ /**
19
+ * Hook for accessing exception state
20
+ */
21
+ export declare const useExceptions: () => {
22
+ exceptions: ExceptionEntity[];
23
+ lastError: ExceptionEntity | null;
24
+ errorCount: number;
25
+ addException: (exception: ExceptionEntity) => void;
26
+ markAsHandled: (exceptionId: string) => void;
27
+ markAsReported: (exceptionId: string) => void;
28
+ clearExceptions: () => void;
29
+ getExceptionsByCategory: (category: string) => ExceptionEntity[];
30
+ getUnhandledExceptions: () => ExceptionEntity[];
31
+ };
32
+ export {};
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ /**
3
+ * Exception Store - Zustand State Management
4
+ * Global exception tracking and error state
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.useExceptions = exports.useExceptionStore = void 0;
8
+ const zustand_1 = require("zustand");
9
+ exports.useExceptionStore = (0, zustand_1.create)((set, get) => ({
10
+ exceptions: [],
11
+ lastError: null,
12
+ errorCount: 0,
13
+ addException: (exception) => {
14
+ const { exceptions } = get();
15
+ set({
16
+ exceptions: [exception, ...exceptions].slice(0, 100), // Keep last 100
17
+ lastError: exception,
18
+ errorCount: get().errorCount + 1,
19
+ });
20
+ },
21
+ markAsHandled: (exceptionId) => {
22
+ const { exceptions } = get();
23
+ const updated = exceptions.map((ex) => ex.id === exceptionId ? { ...ex, handled: true } : ex);
24
+ set({ exceptions: updated });
25
+ },
26
+ markAsReported: (exceptionId) => {
27
+ const { exceptions } = get();
28
+ const updated = exceptions.map((ex) => ex.id === exceptionId ? { ...ex, reported: true } : ex);
29
+ set({ exceptions: updated });
30
+ },
31
+ clearExceptions: () => set({ exceptions: [], lastError: null }),
32
+ getExceptionsByCategory: (category) => {
33
+ const { exceptions } = get();
34
+ return exceptions.filter((ex) => ex.category === category);
35
+ },
36
+ getUnhandledExceptions: () => {
37
+ const { exceptions } = get();
38
+ return exceptions.filter((ex) => !ex.handled);
39
+ },
40
+ }));
41
+ /**
42
+ * Hook for accessing exception state
43
+ */
44
+ const useExceptions = () => {
45
+ const { exceptions, lastError, errorCount, addException, markAsHandled, markAsReported, clearExceptions, getExceptionsByCategory, getUnhandledExceptions, } = (0, exports.useExceptionStore)();
46
+ return {
47
+ exceptions,
48
+ lastError,
49
+ errorCount,
50
+ addException,
51
+ markAsHandled,
52
+ markAsReported,
53
+ clearExceptions,
54
+ getExceptionsByCategory,
55
+ getUnhandledExceptions,
56
+ };
57
+ };
58
+ exports.useExceptions = useExceptions;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Error Boundary Component
3
+ * Catches React errors and provides fallback UI
4
+ */
5
+ import React, { Component, ReactNode } from 'react';
6
+ interface Props {
7
+ children: ReactNode;
8
+ fallback?: ReactNode;
9
+ }
10
+ interface State {
11
+ hasError: boolean;
12
+ error: Error | null;
13
+ }
14
+ export declare class ErrorBoundary extends Component<Props, State> {
15
+ constructor(props: Props);
16
+ static getDerivedStateFromError(error: Error): State;
17
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void;
18
+ handleReset: () => void;
19
+ render(): ReactNode;
20
+ }
21
+ export {};
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ /**
3
+ * Error Boundary Component
4
+ * Catches React errors and provides fallback UI
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.ErrorBoundary = void 0;
41
+ const react_1 = __importStar(require("react"));
42
+ const react_native_1 = require("react-native");
43
+ const ExceptionService_1 = require("../../infrastructure/services/ExceptionService");
44
+ const react_native_design_system_1 = require("@umituz/react-native-design-system");
45
+ class ErrorBoundary extends react_1.Component {
46
+ constructor(props) {
47
+ super(props);
48
+ this.handleReset = () => {
49
+ this.setState({
50
+ hasError: false,
51
+ error: null,
52
+ });
53
+ };
54
+ this.state = {
55
+ hasError: false,
56
+ error: null,
57
+ };
58
+ }
59
+ static getDerivedStateFromError(error) {
60
+ return {
61
+ hasError: true,
62
+ error,
63
+ };
64
+ }
65
+ componentDidCatch(error, errorInfo) {
66
+ // Log error to exception service
67
+ ExceptionService_1.exceptionService.handleFatalError(error, {
68
+ componentStack: errorInfo.componentStack ?? undefined,
69
+ screen: 'ErrorBoundary',
70
+ });
71
+ }
72
+ render() {
73
+ if (this.state.hasError) {
74
+ if (this.props.fallback) {
75
+ return this.props.fallback;
76
+ }
77
+ return (<ErrorDisplay error={this.state.error} onReset={this.handleReset}/>);
78
+ }
79
+ return this.props.children;
80
+ }
81
+ }
82
+ exports.ErrorBoundary = ErrorBoundary;
83
+ const ErrorDisplay = ({ error, onReset }) => {
84
+ const tokens = (0, react_native_design_system_1.useAppDesignTokens)();
85
+ const styles = getStyles(tokens);
86
+ return (<react_native_1.View style={styles.container}>
87
+ <react_native_1.Text style={styles.title}>Something went wrong</react_native_1.Text>
88
+ <react_native_1.Text style={styles.message}>
89
+ {error?.message || 'An unexpected error occurred'}
90
+ </react_native_1.Text>
91
+ <react_native_1.TouchableOpacity style={styles.button} onPress={onReset}>
92
+ <react_native_1.Text style={styles.buttonText}>Try Again</react_native_1.Text>
93
+ </react_native_1.TouchableOpacity>
94
+ </react_native_1.View>);
95
+ };
96
+ const getStyles = (tokens) => react_native_1.StyleSheet.create({
97
+ container: {
98
+ flex: 1,
99
+ justifyContent: 'center',
100
+ alignItems: 'center',
101
+ padding: tokens.spacing.lg,
102
+ backgroundColor: tokens.colors.backgroundPrimary,
103
+ },
104
+ title: {
105
+ fontSize: tokens.typography.headlineSmall.fontSize,
106
+ fontWeight: tokens.typography.headlineSmall.fontWeight,
107
+ marginBottom: tokens.spacing.sm,
108
+ color: tokens.colors.textPrimary,
109
+ },
110
+ message: {
111
+ fontSize: tokens.typography.bodyLarge.fontSize,
112
+ color: tokens.colors.textSecondary,
113
+ textAlign: 'center',
114
+ marginBottom: tokens.spacing.lg,
115
+ },
116
+ button: {
117
+ backgroundColor: tokens.colors.primary,
118
+ paddingHorizontal: tokens.spacing.lg,
119
+ paddingVertical: tokens.spacing.sm,
120
+ borderRadius: tokens.borders.radius.sm,
121
+ },
122
+ buttonText: {
123
+ color: tokens.colors.textInverse,
124
+ fontSize: tokens.typography.bodyLarge.fontSize,
125
+ fontWeight: tokens.typography.labelLarge.fontWeight,
126
+ },
127
+ });
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@umituz/react-native-exception",
3
+ "version": "1.0.0",
4
+ "description": "Exception handling and error tracking for React Native apps",
5
+ "main": "./lib/index.js",
6
+ "types": "./lib/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "typecheck": "tsc --noEmit",
10
+ "lint": "tsc --noEmit",
11
+ "clean": "rm -rf lib",
12
+ "prebuild": "npm run clean",
13
+ "prepublishOnly": "npm run build",
14
+ "version:patch": "npm version patch -m 'chore: release v%s'",
15
+ "version:minor": "npm version minor -m 'chore: release v%s'",
16
+ "version:major": "npm version major -m 'chore: release v%s'"
17
+ },
18
+ "keywords": [
19
+ "react-native",
20
+ "exception",
21
+ "error",
22
+ "error-handling",
23
+ "error-boundary",
24
+ "crash-reporting"
25
+ ],
26
+ "author": "Ümit UZ <umit@umituz.com>",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/umituz/react-native-exception"
31
+ },
32
+ "peerDependencies": {
33
+ "react": ">=18.2.0",
34
+ "react-native": ">=0.74.0",
35
+ "zustand": "^5.0.2",
36
+ "@umituz/react-native-design-system": "^1.8.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "@umituz/react-native-design-system": {
40
+ "optional": false
41
+ }
42
+ },
43
+ "devDependencies": {
44
+ "typescript": "^5.3.3",
45
+ "@types/react": "^18.2.45",
46
+ "@types/react-native": "^0.73.0",
47
+ "react": "^18.2.0",
48
+ "react-native": "^0.74.0",
49
+ "zustand": "^5.0.2",
50
+ "@umituz/react-native-design-system": "^1.8.0"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "files": [
56
+ "lib",
57
+ "src",
58
+ "README.md",
59
+ "LICENSE"
60
+ ]
61
+ }
62
+
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Exception Entity - Domain Layer
3
+ * Pure business logic representation of errors and exceptions
4
+ */
5
+
6
+ export type ExceptionSeverity = 'fatal' | 'error' | 'warning' | 'info';
7
+ export type ExceptionCategory = 'network' | 'validation' | 'authentication' | 'authorization' | 'business-logic' | 'system' | 'storage' | 'unknown';
8
+
9
+ export interface ExceptionContext {
10
+ userId?: string;
11
+ screen?: string;
12
+ action?: string;
13
+ componentStack?: string;
14
+ metadata?: Record<string, any>;
15
+ }
16
+
17
+ export interface ExceptionEntity {
18
+ id: string;
19
+ message: string;
20
+ stack?: string;
21
+ severity: ExceptionSeverity;
22
+ category: ExceptionCategory;
23
+ context: ExceptionContext;
24
+ timestamp: Date;
25
+ handled: boolean;
26
+ reported: boolean;
27
+ }
28
+
29
+ export interface ErrorLog {
30
+ id: string;
31
+ exceptionId: string;
32
+ userId?: string;
33
+ message: string;
34
+ stack?: string;
35
+ severity: ExceptionSeverity;
36
+ category: ExceptionCategory;
37
+ context: ExceptionContext;
38
+ createdAt: Date;
39
+ }
40
+
41
+ /**
42
+ * Factory function to create an exception entity
43
+ */
44
+ export function createException(
45
+ error: Error,
46
+ severity: ExceptionSeverity = 'error',
47
+ category: ExceptionCategory = 'unknown',
48
+ context: ExceptionContext = {}
49
+ ): ExceptionEntity {
50
+ return {
51
+ id: crypto.randomUUID(),
52
+ message: error.message,
53
+ stack: error.stack,
54
+ severity,
55
+ category,
56
+ context,
57
+ timestamp: new Date(),
58
+ handled: false,
59
+ reported: false,
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Factory function to create an error log
65
+ */
66
+ export function createErrorLog(
67
+ exception: ExceptionEntity
68
+ ): ErrorLog {
69
+ return {
70
+ id: crypto.randomUUID(),
71
+ exceptionId: exception.id,
72
+ userId: exception.context.userId,
73
+ message: exception.message,
74
+ stack: exception.stack,
75
+ severity: exception.severity,
76
+ category: exception.category,
77
+ context: exception.context,
78
+ createdAt: new Date(),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Determine if exception should be reported
84
+ */
85
+ export function shouldReportException(exception: ExceptionEntity): boolean {
86
+ // Don't report warnings or info
87
+ if (exception.severity === 'warning' || exception.severity === 'info') {
88
+ return false;
89
+ }
90
+
91
+ // Don't report validation errors (user errors)
92
+ if (exception.category === 'validation') {
93
+ return false;
94
+ }
95
+
96
+ // Report everything else
97
+ return true;
98
+ }
99
+
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Exception Repository Interface
3
+ * Defines contracts for error logging and reporting
4
+ */
5
+
6
+ import type { ExceptionEntity, ErrorLog } from '../entities/ExceptionEntity';
7
+
8
+ export interface ExceptionRepositoryError extends Error {
9
+ code: 'LOG_FAILED' | 'REPORT_FAILED' | 'FETCH_FAILED';
10
+ }
11
+
12
+ export type ExceptionResult<T> = {
13
+ success: true;
14
+ data: T;
15
+ } | {
16
+ success: false;
17
+ error: ExceptionRepositoryError;
18
+ };
19
+
20
+ export interface IExceptionRepository {
21
+ /**
22
+ * Log an exception
23
+ */
24
+ logException(exception: ExceptionEntity): Promise<ExceptionResult<ErrorLog>>;
25
+
26
+ /**
27
+ * Report exception to external service (e.g., Sentry)
28
+ */
29
+ reportException(exception: ExceptionEntity): Promise<ExceptionResult<boolean>>;
30
+
31
+ /**
32
+ * Get error logs for a user
33
+ */
34
+ getErrorLogs(userId: string, limit?: number): Promise<ExceptionResult<ErrorLog[]>>;
35
+
36
+ /**
37
+ * Get recent exceptions
38
+ */
39
+ getRecentExceptions(limit?: number): Promise<ExceptionResult<ExceptionEntity[]>>;
40
+
41
+ /**
42
+ * Clear error logs
43
+ */
44
+ clearErrorLogs(userId: string): Promise<ExceptionResult<boolean>>;
45
+ }
46
+
package/src/index.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @umituz/react-native-exception - Public API
3
+ *
4
+ * Exception handling and error tracking for React Native apps
5
+ *
6
+ * Usage:
7
+ * import { ErrorBoundary, exceptionService, useExceptionStore } from '@umituz/react-native-exception';
8
+ */
9
+
10
+ // =============================================================================
11
+ // DOMAIN LAYER EXPORTS
12
+ // =============================================================================
13
+
14
+ // Entities
15
+ export type {
16
+ ExceptionEntity,
17
+ ErrorLog,
18
+ ExceptionContext,
19
+ ExceptionSeverity,
20
+ ExceptionCategory,
21
+ } from './domain/entities/ExceptionEntity';
22
+ export {
23
+ createException,
24
+ createErrorLog,
25
+ shouldReportException,
26
+ } from './domain/entities/ExceptionEntity';
27
+
28
+ // Repositories
29
+ export type {
30
+ IExceptionRepository,
31
+ ExceptionRepositoryError,
32
+ ExceptionResult,
33
+ } from './domain/repositories/IExceptionRepository';
34
+
35
+ // =============================================================================
36
+ // INFRASTRUCTURE LAYER EXPORTS
37
+ // =============================================================================
38
+
39
+ // State Store (Zustand)
40
+ export { useExceptionStore, useExceptions } from './infrastructure/storage/ExceptionStore';
41
+
42
+ // Services
43
+ export { ExceptionService, exceptionService } from './infrastructure/services/ExceptionService';
44
+
45
+ // =============================================================================
46
+ // PRESENTATION LAYER EXPORTS
47
+ // =============================================================================
48
+
49
+ // Components
50
+ export { ErrorBoundary } from './presentation/components/ErrorBoundary';
51
+
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Exception Service - Infrastructure Layer
3
+ * Centralized exception handling and reporting
4
+ */
5
+
6
+ import type {
7
+ ExceptionEntity,
8
+ ExceptionContext,
9
+ ExceptionSeverity,
10
+ ExceptionCategory,
11
+ } from '../../domain/entities/ExceptionEntity';
12
+ import {
13
+ createException,
14
+ shouldReportException,
15
+ } from '../../domain/entities/ExceptionEntity';
16
+ import { useExceptionStore } from '../storage/ExceptionStore';
17
+
18
+ export class ExceptionService {
19
+ private static instance: ExceptionService;
20
+
21
+ private constructor() {}
22
+
23
+ static getInstance(): ExceptionService {
24
+ if (!ExceptionService.instance) {
25
+ ExceptionService.instance = new ExceptionService();
26
+ }
27
+ return ExceptionService.instance;
28
+ }
29
+
30
+ /**
31
+ * Handle an exception
32
+ */
33
+ handleException(
34
+ error: Error,
35
+ severity: ExceptionSeverity = 'error',
36
+ category: ExceptionCategory = 'unknown',
37
+ context: ExceptionContext = {},
38
+ ): void {
39
+ const exception = createException(error, severity, category, context);
40
+
41
+ // Add to store
42
+ useExceptionStore.getState().addException(exception);
43
+
44
+ // Report to external service if needed
45
+ if (shouldReportException(exception)) {
46
+ this.reportException(exception);
47
+ }
48
+
49
+ // Mark as handled
50
+ useExceptionStore.getState().markAsHandled(exception.id);
51
+ }
52
+
53
+ /**
54
+ * Report exception to external service (e.g., Sentry)
55
+ */
56
+ private async reportException(exception: ExceptionEntity): Promise<void> {
57
+ try {
58
+ // Mark as reported
59
+ useExceptionStore.getState().markAsReported(exception.id);
60
+ } catch (error) {
61
+ // Silent failure
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Handle network errors
67
+ */
68
+ handleNetworkError(error: Error, context: ExceptionContext = {}): void {
69
+ this.handleException(error, 'error', 'network', context);
70
+ }
71
+
72
+ /**
73
+ * Handle validation errors
74
+ */
75
+ handleValidationError(error: Error, context: ExceptionContext = {}): void {
76
+ this.handleException(error, 'warning', 'validation', context);
77
+ }
78
+
79
+ /**
80
+ * Handle storage/permission errors
81
+ */
82
+ handleStorageError(error: Error, context: ExceptionContext = {}): void {
83
+ this.handleException(error, 'error', 'storage', context);
84
+ }
85
+
86
+ /**
87
+ * Handle fatal errors
88
+ */
89
+ handleFatalError(error: Error, context: ExceptionContext = {}): void {
90
+ this.handleException(error, 'fatal', 'system', context);
91
+ }
92
+
93
+ /**
94
+ * Clear all exceptions
95
+ */
96
+ clearExceptions(): void {
97
+ useExceptionStore.getState().clearExceptions();
98
+ }
99
+ }
100
+
101
+ export const exceptionService = ExceptionService.getInstance();
102
+
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Exception Store - Zustand State Management
3
+ * Global exception tracking and error state
4
+ */
5
+
6
+ import { create } from 'zustand';
7
+ import type { ExceptionEntity } from '../../domain/entities/ExceptionEntity';
8
+
9
+ interface ExceptionStore {
10
+ // State
11
+ exceptions: ExceptionEntity[];
12
+ lastError: ExceptionEntity | null;
13
+ errorCount: number;
14
+
15
+ // Actions
16
+ addException: (exception: ExceptionEntity) => void;
17
+ markAsHandled: (exceptionId: string) => void;
18
+ markAsReported: (exceptionId: string) => void;
19
+ clearExceptions: () => void;
20
+ getExceptionsByCategory: (category: string) => ExceptionEntity[];
21
+ getUnhandledExceptions: () => ExceptionEntity[];
22
+ }
23
+
24
+ export const useExceptionStore = create<ExceptionStore>((set, get) => ({
25
+ exceptions: [],
26
+ lastError: null,
27
+ errorCount: 0,
28
+
29
+ addException: (exception) => {
30
+ const { exceptions } = get();
31
+ set({
32
+ exceptions: [exception, ...exceptions].slice(0, 100), // Keep last 100
33
+ lastError: exception,
34
+ errorCount: get().errorCount + 1,
35
+ });
36
+ },
37
+
38
+ markAsHandled: (exceptionId) => {
39
+ const { exceptions } = get();
40
+ const updated = exceptions.map((ex) =>
41
+ ex.id === exceptionId ? { ...ex, handled: true } : ex
42
+ );
43
+ set({ exceptions: updated });
44
+ },
45
+
46
+ markAsReported: (exceptionId) => {
47
+ const { exceptions } = get();
48
+ const updated = exceptions.map((ex) =>
49
+ ex.id === exceptionId ? { ...ex, reported: true } : ex
50
+ );
51
+ set({ exceptions: updated });
52
+ },
53
+
54
+ clearExceptions: () => set({ exceptions: [], lastError: null }),
55
+
56
+ getExceptionsByCategory: (category) => {
57
+ const { exceptions } = get();
58
+ return exceptions.filter((ex) => ex.category === category);
59
+ },
60
+
61
+ getUnhandledExceptions: () => {
62
+ const { exceptions } = get();
63
+ return exceptions.filter((ex) => !ex.handled);
64
+ },
65
+ }));
66
+
67
+ /**
68
+ * Hook for accessing exception state
69
+ */
70
+ export const useExceptions = () => {
71
+ const {
72
+ exceptions,
73
+ lastError,
74
+ errorCount,
75
+ addException,
76
+ markAsHandled,
77
+ markAsReported,
78
+ clearExceptions,
79
+ getExceptionsByCategory,
80
+ getUnhandledExceptions,
81
+ } = useExceptionStore();
82
+
83
+ return {
84
+ exceptions,
85
+ lastError,
86
+ errorCount,
87
+ addException,
88
+ markAsHandled,
89
+ markAsReported,
90
+ clearExceptions,
91
+ getExceptionsByCategory,
92
+ getUnhandledExceptions,
93
+ };
94
+ };
95
+
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Error Boundary Component
3
+ * Catches React errors and provides fallback UI
4
+ */
5
+
6
+ import React, { Component, ReactNode } from 'react';
7
+ import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
8
+ import { exceptionService } from '../../infrastructure/services/ExceptionService';
9
+ import { useAppDesignTokens } from '@umituz/react-native-design-system';
10
+
11
+ interface Props {
12
+ children: ReactNode;
13
+ fallback?: ReactNode;
14
+ }
15
+
16
+ interface State {
17
+ hasError: boolean;
18
+ error: Error | null;
19
+ }
20
+
21
+ export class ErrorBoundary extends Component<Props, State> {
22
+ constructor(props: Props) {
23
+ super(props);
24
+ this.state = {
25
+ hasError: false,
26
+ error: null,
27
+ };
28
+ }
29
+
30
+ static getDerivedStateFromError(error: Error): State {
31
+ return {
32
+ hasError: true,
33
+ error,
34
+ };
35
+ }
36
+
37
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
38
+ // Log error to exception service
39
+ exceptionService.handleFatalError(error, {
40
+ componentStack: errorInfo.componentStack ?? undefined,
41
+ screen: 'ErrorBoundary',
42
+ });
43
+ }
44
+
45
+ handleReset = (): void => {
46
+ this.setState({
47
+ hasError: false,
48
+ error: null,
49
+ });
50
+ };
51
+
52
+ render(): ReactNode {
53
+ if (this.state.hasError) {
54
+ if (this.props.fallback) {
55
+ return this.props.fallback;
56
+ }
57
+
58
+ return (
59
+ <ErrorDisplay error={this.state.error} onReset={this.handleReset} />
60
+ );
61
+ }
62
+
63
+ return this.props.children;
64
+ }
65
+ }
66
+
67
+ interface ErrorDisplayProps {
68
+ error: Error | null;
69
+ onReset: () => void;
70
+ }
71
+
72
+ const ErrorDisplay: React.FC<ErrorDisplayProps> = ({ error, onReset }) => {
73
+ const tokens = useAppDesignTokens();
74
+ const styles = getStyles(tokens);
75
+
76
+ return (
77
+ <View style={styles.container}>
78
+ <Text style={styles.title}>Something went wrong</Text>
79
+ <Text style={styles.message}>
80
+ {error?.message || 'An unexpected error occurred'}
81
+ </Text>
82
+ <TouchableOpacity style={styles.button} onPress={onReset}>
83
+ <Text style={styles.buttonText}>Try Again</Text>
84
+ </TouchableOpacity>
85
+ </View>
86
+ );
87
+ };
88
+
89
+ const getStyles = (tokens: ReturnType<typeof useAppDesignTokens>) =>
90
+ StyleSheet.create({
91
+ container: {
92
+ flex: 1,
93
+ justifyContent: 'center',
94
+ alignItems: 'center',
95
+ padding: tokens.spacing.lg,
96
+ backgroundColor: tokens.colors.backgroundPrimary,
97
+ },
98
+ title: {
99
+ fontSize: tokens.typography.headlineSmall.fontSize,
100
+ fontWeight: tokens.typography.headlineSmall.fontWeight,
101
+ marginBottom: tokens.spacing.sm,
102
+ color: tokens.colors.textPrimary,
103
+ },
104
+ message: {
105
+ fontSize: tokens.typography.bodyLarge.fontSize,
106
+ color: tokens.colors.textSecondary,
107
+ textAlign: 'center',
108
+ marginBottom: tokens.spacing.lg,
109
+ },
110
+ button: {
111
+ backgroundColor: tokens.colors.primary,
112
+ paddingHorizontal: tokens.spacing.lg,
113
+ paddingVertical: tokens.spacing.sm,
114
+ borderRadius: tokens.borders.radius.sm,
115
+ },
116
+ buttonText: {
117
+ color: tokens.colors.textInverse,
118
+ fontSize: tokens.typography.bodyLarge.fontSize,
119
+ fontWeight: tokens.typography.labelLarge.fontWeight,
120
+ },
121
+ });
122
+