@ad-execute-manager/serializable-error
v2.0.5
Published
An error class that can be serialized to JSON for easy transmission and storage.
Maintainers
Readme
@ad-execute-manager/serializable-error
An error class that can be serialized to JSON for easy transmission and storage.
Installation
npm install @ad-execute-manager/serializable-errorFeatures
- JSON Serialization: Convert error objects to JSON for easy transmission
- Custom Properties: Support for custom error properties like errorCode and errMsg
- Full Error Information: Preserves name, message, stack, and custom properties
- TypeScript Support: Includes TypeScript type definitions
- Standard Error Interface: Extends native Error class for compatibility
Usage
Basic Usage
import { SerializableError } from '@ad-execute-manager/serializable-error';
// Create a serializable error
const error = new SerializableError('Something went wrong', {
errorCode: 500,
errMsg: 'Internal server error'
});
console.log(error.name); // 'SerializableError'
console.log(error.message); // 'Something went wrong'
console.log(error.errorCode); // 500
console.log(error.errMsg); // 'Internal server error'
// Convert to JSON
const jsonError = error.toJSON();
console.log(jsonError);
// {
// name: 'SerializableError',
// message: 'Something went wrong',
// stack: '...',
// errMsg: 'Internal server error',
// errorCode: 500
// }Error Handling in API
import { SerializableError } from '@ad-execute-manager/serializable-error';
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new SerializableError('API request failed', {
errorCode: response.status,
errMsg: response.statusText
});
}
return await response.json();
} catch (error) {
if (error instanceof SerializableError) {
// Send error to monitoring system
sendToMonitoring(error.toJSON());
// Return user-friendly error
return {
success: false,
error: {
code: error.errorCode,
message: error.errMsg || error.message
}
};
}
throw error;
}
}Custom Error Classes
import { SerializableError } from '@ad-execute-manager/serializable-error';
class ValidationError extends SerializableError {
constructor(message, field) {
super(message, {
errorCode: 400,
errMsg: 'Validation failed',
field
});
this.name = 'ValidationError';
}
}
class AuthenticationError extends SerializableError {
constructor(message) {
super(message, {
errorCode: 401,
errMsg: 'Authentication failed'
});
this.name = 'AuthenticationError';
}
}
// Usage
try {
if (!user.email) {
throw new ValidationError('Email is required', 'email');
}
} catch (error) {
console.log(error.toJSON());
// {
// name: 'ValidationError',
// message: 'Email is required',
// stack: '...',
// errMsg: 'Validation failed',
// errorCode: 400,
// field: 'email'
// }
}Error Logging and Monitoring
import { SerializableError } from '@ad-execute-manager/serializable-error';
function logError(error) {
// Convert to JSON for logging
const errorData = error instanceof SerializableError
? error.toJSON()
: {
name: error.name,
message: error.message,
stack: error.stack
};
// Send to logging service
fetch('/api/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(errorData)
});
}
// Usage
try {
// Some operation that might fail
} catch (error) {
const serializableError = new SerializableError('Operation failed', {
errorCode: 500,
errMsg: error.message
});
logError(serializableError);
}Error Transmission
import { SerializableError } from '@ad-execute-manager/serializable-error';
// Worker thread or postMessage
const worker = new Worker('worker.js');
worker.onerror = (error) => {
const serializableError = new SerializableError('Worker error', {
errorCode: 500,
errMsg: error.message
});
// Send error to main thread
postMessage({
type: 'error',
error: serializableError.toJSON()
});
};
// Receive error in main thread
onmessage = (event) => {
if (event.data.type === 'error') {
console.log('Received error:', event.data.error);
}
};API
Constructor
new SerializableError(message, options)- message (String): Error message
- options (Object, optional): Configuration options
- errMsg (String): Error description
- errorCode (Number): Error code
- Additional custom properties can be added
Methods
- toJSON(): Returns a JSON-serializable object with all error properties
Properties
- name (String): The name of the error class
- message (String): The error message
- stack (String): The stack trace
- errMsg (String): Custom error description (from options)
- errorCode (Number): Custom error code (from options)
- [customProps]: Any additional custom properties passed in options
Examples
Real-world Use Cases
1. API Error Handling
import { SerializableError } from '@ad-execute-manager/serializable-error';
class APIError extends SerializableError {
constructor(message, status, data) {
super(message, {
errorCode: status,
errMsg: `API Error: ${status}`,
data
});
this.name = 'APIError';
}
}
async function makeRequest(url) {
const response = await fetch(url);
if (!response.ok) {
throw new APIError(
'Request failed',
response.status,
await response.json()
);
}
return response.json();
}2. Database Error Handling
import { SerializableError } from '@ad-execute-manager/serializable-error';
class DatabaseError extends SerializableError {
constructor(message, query, originalError) {
super(message, {
errorCode: 500,
errMsg: 'Database operation failed',
query,
originalError: originalError.message
});
this.name = 'DatabaseError';
}
}
async function queryDatabase(sql) {
try {
return await db.query(sql);
} catch (error) {
throw new DatabaseError('Query failed', sql, error);
}
}3. Form Validation
import { SerializableError } from '@ad-execute-manager/serializable-error';
class FormValidationError extends SerializableError {
constructor(message, fields) {
super(message, {
errorCode: 422,
errMsg: 'Form validation failed',
fields
});
this.name = 'FormValidationError';
}
}
function validateForm(formData) {
const errors = {};
if (!formData.email) errors.email = 'Email is required';
if (!formData.password) errors.password = 'Password is required';
if (Object.keys(errors).length > 0) {
throw new FormValidationError('Validation failed', errors);
}
return true;
}License
MIT
