Comprehensive error handling system for Plyaz ecosystem with standardized error classes, validation, input sanitization & security. Supports frontend, backend & blockchain integration.
npm install @plyaz/errorsComprehensive error handling system for the Plyaz ecosystem with standardized error classes, validation, input sanitization & security support for frontend, backend & blockchain integration.
``bash`
pnpm add @plyaz/errors
`typescript
import { ValidationError, ApiError, AuthError } from '@plyaz/errors';
// Throw a validation error
throw new ValidationError('VALIDATION_ERROR', 'en', {
field: 'email',
message: 'Invalid email format'
});
// Throw an API error
throw new ApiError('NOT_FOUND', 404, {
entity: 'User',
id: '123'
});
// Throw an authentication error
throw new AuthError('AUTH_TOKEN_EXPIRED');
`
`typescript
import { useErrorHandler, ErrorBoundary } from '@plyaz/errors/frontend';
function MyComponent() {
const { handleError, isAuthError } = useErrorHandler();
const fetchData = async () => {
try {
// API call
} catch (error) {
handleError(error, {
notFound: () => navigate('/404'),
unauthorized: () => navigate('/login'),
default: (err) => console.error(err)
});
}
};
return (
{/ Your component /}
);
}
`
`typescript
import { GlobalErrorFilter } from '@plyaz/errors/backend';
// In main.ts
app.useGlobalFilters(new GlobalErrorFilter());
// In a service
import { NotFoundError, ConflictError } from '@plyaz/errors';
async findUser(id: string) {
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) {
throw new NotFoundError('User not found', { userId: id });
}
return user;
}
`
``
BaseError
├── ValidationError - Input validation failures
├── AuthError - Authentication/authorization errors
│ ├── UnauthorizedError
│ └── ForbiddenError
├── ApiError - API-related errors
│ ├── NotFoundError
│ ├── ConflictError
│ └── TimeoutError
├── BusinessError - Business logic errors
└── BlockchainError - Blockchain-specific errors
├── TransactionError
├── WalletError
└── ContractError
All errors include:
- name - Error class namemessage
- - Human-readable message (i18n supported)code
- - Application error code (e.g., "AUTH_TOKEN_EXPIRED")statusCode
- - HTTP status codetimestamp
- - ISO timestamp of occurrencedetails
- - Additional context datacause
- - Original error if wrappingcorrelationId
- - Request tracking IDstack
- - Stack trace (dev only)
`typescript
import { BusinessError } from '@plyaz/errors';
export class InsufficientFundsError extends BusinessError {
constructor(details?: any) {
super('INSUFFICIENT_FUNDS', 'en', details);
this.statusCode = 402;
}
}
// Usage
throw new InsufficientFundsError({
available: 100,
required: 150,
currency: 'USD'
});
`
Protect against XSS and SQL injection:
`typescript
import { sanitizeHtml, sanitizeSql } from '@plyaz/errors/sanitizers';
// Sanitize HTML input
const safeHtml = sanitizeHtml(userInput, {
allowedTags: ['b', 'i', 'em', 'strong'],
allowedAttributes: {}
});
// Sanitize SQL input
const safeSqlInput = sanitizeSql(userQuery);
`
Transport errors between services:
`typescript
import { serializeError, deserializeError } from '@plyaz/errors/serializers';
// Convert error to plain object
const serialized = serializeError(error);
// Send over network...
// Recreate error instance
const error = deserializeError(serialized);
`
Works seamlessly with @plyaz/logger:
`typescript
import { logError } from '@plyaz/errors/utils';
import { logger } from '@plyaz/logger';
try {
// Some operation
} catch (error) {
logError(logger, error, {
userId: user.id,
context: 'user-creation',
correlationId: request.id
});
}
`
All errors follow this structure:
`typescript
interface ErrorResponse {
statusCode: number; // HTTP status code
errorCode: string; // Application error code
message: string; // Human-readable message
errors?: ErrorDetail[]; // Detailed validation errors
correlationId?: string; // Request tracing ID
timestamp: string; // ISO timestamp
}
interface ErrorDetail {
field?: string; // Field with error
message: string; // Error message
errorCode: string; // Specific error code
context?: any; // Additional context
}
`
- Invalid login credentials
- AUTH_TOKEN_EXPIRED - Authentication token expired
- AUTH_TOKEN_INVALID - Invalid authentication token
- AUTH_INSUFFICIENT_PERMISSIONS - Lacks required permissions$3
- VALIDATION_ERROR - General validation failure
- REQUIRED_FIELD_MISSING - Required field not provided
- INVALID_FORMAT - Field format invalid
- STRING_TOO_SHORT - String below minimum length
- STRING_TOO_LONG - String exceeds maximum length$3
- DB_ENTITY_NOT_FOUND - Entity not found
- DB_DUPLICATE_ENTRY - Unique constraint violation
- DB_TRANSACTION_FAILED - Transaction failure$3
- BLOCKCHAIN_CONNECTION_ERROR - Blockchain connection failed
- TRANSACTION_FAILED - Transaction failed
- INSUFFICIENT_FUNDS - Insufficient fundsDevelopment Commands
`bash
Development
pnpm dev # Start development with watch mode
pnpm build # Build for production
pnpm clean # Clean dist directoryTesting
pnpm test # Run tests once
pnpm test:watch # Run tests in watch mode
pnpm test:coverage # Run tests with coverage
pnpm test:ui # Open Vitest UICode Quality
pnpm lint # Run ESLint
pnpm lint:fix # Auto-fix linting issues
pnpm format # Format code with Prettier
pnpm type:check # TypeScript type checkingSecurity
pnpm security:check # Security audit
pnpm audit:fix # Auto-fix vulnerabilities
`Package Dependencies
Per Plyaz monorepo architecture:
$3
- @plyaz/types - Error type definitions
- @plyaz/utils - Utility functions
- @plyaz/config - Configuration constants
- @plyaz/translations - i18n error messages
- @plyaz/logger - Error logging integration$3
- @plyaz/api, @plyaz/web3, @plyaz/ui, @plyaz/hooks, @plyaz/store`When adding new error types:
1. Extend from appropriate base class
2. Add error code to constants
3. Add translations to @plyaz/translations
4. Update type definitions in @plyaz/types
5. Add unit tests with 90% coverage minimum
6. Document in README with examples
ISC