@plyaz/errors
v1.5.0
Published
Comprehensive error handling system for Plyaz ecosystem with standardized error classes, validation, input sanitization & security. Supports frontend, backend & blockchain integration.
Downloads
1,328
Keywords
Readme
@plyaz/errors
Comprehensive error handling system for the Plyaz ecosystem with standardized error classes, validation, input sanitization & security support for frontend, backend & blockchain integration.
Installation
pnpm add @plyaz/errorsQuick Start
Basic Error Usage
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');Frontend Error Handling
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 (
<ErrorBoundary fallback={<ErrorPage />}>
{/* Your component */}
</ErrorBoundary>
);
}Backend Error Handling (NestJS)
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;
}Error exceptions
Base Error Hierarchy
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
└── ContractErrorError Properties
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)
Creating Custom Errors
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'
});Input Sanitization
Protect against XSS and SQL injection:
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);Error Serialization
Transport errors between services:
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);Logger Integration
Works seamlessly with @plyaz/logger:
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
});
}Standard Error Response Format
All errors follow this structure:
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
}Common Error Codes
Authentication Errors
AUTH_INVALID_CREDENTIALS- Invalid login credentialsAUTH_TOKEN_EXPIRED- Authentication token expiredAUTH_TOKEN_INVALID- Invalid authentication tokenAUTH_INSUFFICIENT_PERMISSIONS- Lacks required permissions
Validation Errors
VALIDATION_ERROR- General validation failureREQUIRED_FIELD_MISSING- Required field not providedINVALID_FORMAT- Field format invalidSTRING_TOO_SHORT- String below minimum lengthSTRING_TOO_LONG- String exceeds maximum length
Database Errors
DB_ENTITY_NOT_FOUND- Entity not foundDB_DUPLICATE_ENTRY- Unique constraint violationDB_TRANSACTION_FAILED- Transaction failure
Blockchain Errors
BLOCKCHAIN_CONNECTION_ERROR- Blockchain connection failedTRANSACTION_FAILED- Transaction failedINSUFFICIENT_FUNDS- Insufficient funds
Development Commands
# Development
pnpm dev # Start development with watch mode
pnpm build # Build for production
pnpm clean # Clean dist directory
# Testing
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 UI
# Code Quality
pnpm lint # Run ESLint
pnpm lint:fix # Auto-fix linting issues
pnpm format # Format code with Prettier
pnpm type:check # TypeScript type checking
# Security
pnpm security:check # Security audit
pnpm audit:fix # Auto-fix vulnerabilitiesPackage Dependencies
Per Plyaz monorepo architecture:
Can Import From
- @plyaz/types - Error type definitions
- @plyaz/utils - Utility functions
- @plyaz/config - Configuration constants
- @plyaz/translations - i18n error messages
- @plyaz/logger - Error logging integration
Cannot Import From
@plyaz/api,@plyaz/web3,@plyaz/ui,@plyaz/hooks,@plyaz/store
Contributing
When adding new error types:
- Extend from appropriate base class
- Add error code to constants
- Add translations to @plyaz/translations
- Update type definitions in @plyaz/types
- Add unit tests with 90% coverage minimum
- Document in README with examples
License
ISC
