errormail
v0.0.14
Published
auto-matic error service to send emails when an error occurs
Downloads
360
Readme
ErrorMail
Automatic error service to send emails when an error occurs in React components or JavaScript functions.
Installation
npm install errormailNote: This package requires React as a peer dependency. Make sure you have React installed in your project.
Features
- React Error Boundary - Wrap React components to catch and report errors
- Function Wrappers - Wrap async/sync functions to automatically catch and report errors
- Email Reporting - Automatically sends error information to your API endpoint
- Configurable - Easy configuration for API endpoint, credentials, and email addresses
- Rate Limiting - Prevent duplicate errors from flooding your inbox
- Breadcrumbs - Track user actions leading up to errors
- Environment Info - Automatically capture browser, device, and runtime information
- Severity Levels - Categorize errors as debug, info, warning, error, or fatal
Quick Start
1. Configure Error Reporting
const { configureErrorReporting, initBreadcrumbs } = require('errormail');
configureErrorReporting({
apiKey: 'your-api-key-here',
emailTo: '[email protected]',
// Rate limiting - prevent duplicate errors within 5 seconds
rateLimitMs: 5000,
// Include breadcrumbs in error reports (default: true)
includeBreadcrumbs: true,
// Include environment info in error reports (default: true)
includeEnvironment: true,
// Maximum breadcrumbs to include (default: 30)
maxBreadcrumbs: 20,
});
// Initialize automatic breadcrumb collection (browser only)
initBreadcrumbs();2. Wrap React Components
const React = require('react');
const { ErrorBoundary } = require('errormail');
function App() {
return (
<ErrorBoundary>
<Button onClick={() => {Throw new Error("Error")}}>
Error button
</Button>
</ErrorBoundary>
);
}const React = require('react');
const { ErrorBoundary, ErrorLevel } = require('errormail');
function MyComponent() {
return <div>My Component</div>;
}
function App() {
return (
<ErrorBoundary
emailTo="[email protected]"
level={ErrorLevel.FATAL} // Treat as fatal error
fallback={(error) => (
<div>
<h1>Something went wrong</h1>
<p>{error.message}</p>
</div>
)}
>
<MyComponent />
</ErrorBoundary>
);
}3. Wrap Functions with errormail
const { errormail } = require('errormail');
async function fetchUserData(userId) {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error('Failed to fetch user');
}
return response.json();
}
// Curried usage - call errormail(emailTo) at the end
const safeFetchUserData = errormail('[email protected]')(fetchUserData);
// Create reusable wrappers
const wrapForAdmin = errormail('[email protected]');
const wrapForDevOps = errormail('[email protected]');
const safeFunction1 = wrapForAdmin(fetchUserData);
const safeFunction2 = wrapForDevOps(processData);Breadcrumbs
Track user actions leading up to an error. Breadcrumbs are automatically included in error reports.
const { addBreadcrumb, getBreadcrumbs, clearBreadcrumbs, BreadcrumbCategory } = require('errormail');
// Add manual breadcrumbs
addBreadcrumb('User logged in', BreadcrumbCategory.USER, { userId: 123 });
addBreadcrumb('Viewed dashboard', BreadcrumbCategory.NAVIGATION, { page: '/dashboard' });
addBreadcrumb('API call', BreadcrumbCategory.HTTP, { endpoint: '/api/users' });
// Get all breadcrumbs
console.log(getBreadcrumbs());
// Clear breadcrumbs (e.g., on logout)
clearBreadcrumbs();Breadcrumb Categories
BreadcrumbCategory.UI- User interface interactions (clicks, etc.)BreadcrumbCategory.NAVIGATION- Page navigationBreadcrumbCategory.HTTP- HTTP requestsBreadcrumbCategory.CONSOLE- Console messagesBreadcrumbCategory.USER- User actionsBreadcrumbCategory.MANUAL- Manual breadcrumbs (default)
Automatic Breadcrumb Collection
Call initBreadcrumbs() to automatically track:
- Click events
- Navigation (pushState, popstate)
- Fetch requests and responses
- Console errors and warnings
Severity Levels
Capture events at different severity levels:
const {
captureDebug,
captureInfo,
captureWarning,
captureError,
captureFatal,
captureMessage,
ErrorLevel
} = require('errormail');
// Debug (development info)
captureDebug('Starting sync process', { syncId: 'abc123' });
// Info (general information)
captureInfo('User completed onboarding', { userId: 123 });
// Warning (potential issues)
captureWarning('API response slow', { responseTime: 3500 });
// Error (something went wrong)
captureError(new Error('Failed to save'), { userId: 123 });
// Fatal (critical failures)
captureFatal(new Error('Database connection lost'));
// Custom level
captureMessage('Custom event', ErrorLevel.INFO, { data: 'value' });Error Levels
ErrorLevel.DEBUG- Debug informationErrorLevel.INFO- General informationErrorLevel.WARNING- Potential issuesErrorLevel.ERROR- Errors (default)ErrorLevel.FATAL- Critical failures
Environment Info
Environment information is automatically captured and included in error reports:
const { getEnvironmentInfo } = require('errormail');
const env = getEnvironmentInfo();
console.log(env);Browser Environment
{
"runtime": "browser",
"url": "https://example.com/page",
"userAgent": "Mozilla/5.0...",
"browser": "Chrome",
"browserVersion": "120",
"os": "macOS",
"platform": "MacIntel",
"language": "en-US",
"screenSize": "1920x1080",
"viewportSize": "1200x800",
"devicePixelRatio": 2,
"timezone": "America/New_York",
"onLine": true
}Node.js Environment
{
"runtime": "node",
"nodeVersion": "v20.10.0",
"platform": "darwin",
"arch": "arm64",
"memoryUsage": { "heapUsed": 12345678 }
}Rate Limiting
Prevent duplicate errors from being sent within a time window:
configureErrorReporting({
rateLimitMs: 5000, // 5 seconds (default)
});If the same error (same message and stack trace location) occurs within the rate limit window, it will be skipped.
API Reference
configureErrorReporting(config)
Configure the error reporting service globally.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| apiKey | string | '' | API key for authentication |
| emailTo | string | '' | Default email address |
| rateLimitMs | number | 5000 | Rate limit in milliseconds |
| includeBreadcrumbs | boolean | true | Include breadcrumbs in reports |
| includeEnvironment | boolean | true | Include environment info |
| maxBreadcrumbs | number | 30 | Max breadcrumbs to include |
Note: The API endpoint is hardcoded to http://localhost:82/v1/api/email and cannot be changed.
ErrorBoundary
React component that catches errors in child components.
| Prop | Type | Description |
|------|------|-------------|
| emailTo | string | Email address (overrides default) |
| level | ErrorLevel | Severity level for caught errors |
| fallback | function | (error) => ReactNode for fallback UI |
| fallbackComponent | Component | Component to render on error |
| errorService | ErrorReportingService | Custom error service instance |
| children | ReactNode | Child components to wrap |
errormail(emailToOrFn, fnOrOptions, options)
Wraps an async function to catch and report errors.
Usage Patterns:
// 1. Curried (recommended)
const safeFn = errormail('[email protected]')(myFunction);
// 2. Direct wrapping
const safeFn = errormail('[email protected]', myFunction);
// 3. Full options
const safeFn = errormail(myFunction, {
emailTo: '[email protected]',
functionName: 'myFunction',
level: ErrorLevel.ERROR,
context: { module: 'myModule' },
includeArgs: true,
rethrow: true
});Breadcrumb Functions
| Function | Description |
|----------|-------------|
| addBreadcrumb(message, category, data, level) | Add a breadcrumb |
| getBreadcrumbs() | Get all breadcrumbs |
| clearBreadcrumbs() | Clear all breadcrumbs |
| initBreadcrumbs() | Initialize automatic collection |
Capture Functions
| Function | Description |
|----------|-------------|
| captureDebug(message, context) | Capture debug message |
| captureInfo(message, context) | Capture info message |
| captureWarning(message, context) | Capture warning |
| captureError(error, context) | Capture error |
| captureFatal(error, context) | Capture fatal error |
| captureMessage(message, level, context) | Capture with custom level |
Other Functions
| Function | Description |
|----------|-------------|
| getEnvironmentInfo() | Get environment information |
| wrapSyncFunction(fn, options) | Wrap synchronous function |
| withErrorBoundary(Component, options) | HOC for ErrorBoundary |
API Endpoint Format
The library sends POST requests to your API endpoint:
Headers:
Content-Type: application/jsonapi-key: <your-api-key>
Body:
{
"message": "Error message",
"stack": "Error stack trace",
"name": "Error",
"level": "error",
"timestamp": "2024-01-01T00:00:00.000Z",
"emailTo": "[email protected]",
"functionName": "fetchUserData",
"componentStack": "...",
"environment": {
"runtime": "browser",
"url": "https://example.com",
"browser": "Chrome",
"os": "macOS"
},
"breadcrumbs": [
{
"message": "User clicked button",
"category": "ui",
"timestamp": "2024-01-01T00:00:00.000Z"
}
]
}Examples
See example.js for more detailed usage examples.
License
ISC
