tryError Documentation
Sentry & Vercel Analytics Integration
Learn how to integrate tryError with popular error tracking and analytics services in your Next.js application.
Why integrate? While tryError provides excellent error handling, services like Sentry and Vercel Analytics offer centralized dashboards, alerting, and team collaboration features that complement tryError perfectly.
Sentry Integration
Sentry provides comprehensive error tracking with features like release tracking, performance monitoring, and session replay. Here's how to integrate it with tryError.
Install Sentry
First, install and configure Sentry in your Next.js app
Terminalbash
1# Install Sentry
2pnpm add @sentry/nextjs
3
4# Run the configuration wizard
5npx @sentry/wizard@latest -i nextjs
The wizard will create the necessary configuration files and set up your Sentry project.
Vercel Analytics Integration
Track error metrics and patterns using Vercel Analytics custom events.
Error Metrics Tracking
Send error data to Vercel Analytics for monitoring
lib/analytics-integration.tstypescript
1import { track } from '@vercel/analytics';
2import { TryError } from '@try-error/core';
3
4export function trackError(error: TryError) {
5 // Track basic error event
6 track('error_occurred', {
7 type: error.type,
8 source: error.source || 'unknown',
9 hasContext: !!error.context,
10 timestamp: error.timestamp,
11 });
12
13 // Track specific error patterns
14 if (error.type.includes('API')) {
15 track('api_error', {
16 endpoint: error.context?.endpoint as string,
17 statusCode: error.context?.statusCode as number,
18 duration: error.context?.duration as number,
19 });
20 }
21
22 if (error.type.includes('Validation')) {
23 track('validation_error', {
24 fields: Object.keys(error.context?.errors || {}),
25 formId: error.context?.formId as string,
26 });
27 }
28
29 // Track error recovery attempts
30 if (error.context?.retryCount) {
31 track('error_retry', {
32 type: error.type,
33 attempt: error.context.retryCount as number,
34 success: error.context.retrySuccess as boolean,
35 });
36 }
37}
Complete Integration Example
Production-Ready Setup
A complete example integrating tryError with Sentry and Vercel Analytics
lib/error-management.tstypescript
1import { setupNextJs, TryError } from '@try-error/core';
2import * as Sentry from '@sentry/nextjs';
3import { track } from '@vercel/analytics';
4
5// Initialize error management
6export function initializeErrorManagement() {
7 setupNextJs({
8 // Base configuration
9 captureStackTrace: process.env.NODE_ENV === 'development',
10 includeSource: true,
11
12 environmentHandlers: {
13 server: createServerHandler(),
14 client: createClientHandler(),
15 edge: createEdgeHandler(),
16 },
17 });
18}
19
20// Server-side handler with logging
21function createServerHandler() {
22 return (error: TryError) => {
23 // Log to console in development
24 if (process.env.NODE_ENV === 'development') {
25 console.error('[Server Error]', error);
26 }
27
28 // Send to Sentry
29 Sentry.withScope((scope) => {
30 scope.setTag('runtime', 'server');
31 scope.setLevel(getSeverityLevel(error));
32 scope.setContext('error_details', {
33 type: error.type,
34 source: error.source,
35 timestamp: error.timestamp,
36 });
37
38 Sentry.captureException(error);
39 });
40
41 // Track metrics
42 track('server_error', {
43 type: error.type,
44 source: error.source || 'unknown',
45 });
46
47 // Log to your server logging service
48 if (global.logger) {
49 global.logger.error({
50 message: error.message,
51 type: error.type,
52 context: error.context,
53 stack: error.stack,
54 });
55 }
56
57 return error;
58 };
59}
60
61// Client-side handler with user context
62function createClientHandler() {
63 return (error: TryError) => {
64 // Development logging
65 if (process.env.NODE_ENV === 'development') {
66 console.error('[Client Error]', error);
67 }
68
69 // Enrich with user context
70 const user = getCurrentUser();
71 if (user) {
72 Sentry.setUser({ id: user.id, email: user.email });
73 }
74
75 // Send to Sentry
76 Sentry.captureException(error, {
77 tags: {
78 runtime: 'client',
79 errorType: error.type,
80 browser: navigator.userAgent,
81 },
82 extra: {
83 source: error.source,
84 url: window.location.href,
85 },
86 });
87
88 // Track in analytics
89 track('client_error', {
90 type: error.type,
91 page: window.location.pathname,
92 });
93
94 return error;
95 };
96}
97
98// Edge handler with minimal overhead
99function createEdgeHandler() {
100 return (error: TryError) => {
101 // Minimal Sentry integration for edge
102 Sentry.captureException(error, {
103 tags: { runtime: 'edge' },
104 });
105
106 // Simple metrics
107 track('edge_error', { type: error.type });
108
109 return error;
110 };
111}
112
113// Helper functions
114function getSeverityLevel(error: TryError): Sentry.SeverityLevel {
115 if (error.type.includes('Critical')) return 'fatal';
116 if (error.type.includes('Warning')) return 'warning';
117 if (error.type.includes('Info')) return 'info';
118 return 'error';
119}
120
121function getCurrentUser() {
122 // Your auth logic here
123 return null;
124}
app/layout.tsxtypescript
1import { initializeErrorManagement } from '@/lib/error-management';
2
3// Initialize once at the app entry point
4initializeErrorManagement();
5
6export default function RootLayout({
7 children,
8}: {
9 children: React.ReactNode;
10}) {
11 return (
12 <html lang="en">
13 <body>{children}</body>
14 </html>
15 );
16}
Best Practices
1. Don't Send Sensitive Data
Be careful about what context you send to external services, especially on the client side.
1// ❌ Bad: Sending sensitive data
2const error = createError({
3 type: 'PaymentError',
4 message: 'Payment failed',
5 context: {
6 creditCardNumber: user.card, // Never do this!
7 cvv: user.cvv,
8 }
9});
10
11// ✅ Good: Send only necessary data
12const error = createError({
13 type: 'PaymentError',
14 message: 'Payment failed',
15 context: {
16 userId: user.id,
17 amount: transaction.amount,
18 currency: transaction.currency,
19 }
20});
2. Use Error Types for Grouping
Consistent error types help with grouping and filtering in Sentry and analytics dashboards.
1// Define consistent error types
2export const ErrorTypes = {
3 // API Errors
4 API_TIMEOUT: 'ApiTimeoutError',
5 API_VALIDATION: 'ApiValidationError',
6 API_AUTH: 'ApiAuthError',
7
8 // User Errors
9 USER_INPUT: 'UserInputError',
10 USER_PERMISSION: 'UserPermissionError',
11
12 // System Errors
13 SYSTEM_DATABASE: 'SystemDatabaseError',
14 SYSTEM_NETWORK: 'SystemNetworkError',
15} as const;
3. Add Meaningful Context
Context helps with debugging but should be structured and meaningful.
1// ✅ Good: Structured, meaningful context
2const error = createError({
3 type: 'ApiError',
4 message: 'Failed to fetch user data',
5 context: {
6 endpoint: '/api/users/123',
7 method: 'GET',
8 statusCode: 500,
9 duration: 1234,
10 retryCount: 3,
11 userId: '123',
12 }
13});